diff --git a/proposals/render/2026-10-30/README.md b/proposals/render/2026-10-30/README.md index 21d831e3a..45c4453a2 100644 --- a/proposals/render/2026-10-30/README.md +++ b/proposals/render/2026-10-30/README.md @@ -235,3 +235,13 @@ 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. + +## Progressive CPU compatibility WIP, isolated fixture and exact C28 host — 31 October + +[Separated source packages and exact bindings](../2026-10-31/progressive-compatibility-wip/README.md) +preserve 34 uncompiled WIP candidates plus the actual earlier formatted C28 host +(35 source files). C28: 28 PASS / 1 font-fixture FAIL / 954 UNRUN, two actual +CPU-supported markers; no postchecks/native acceptance. The corrected test is +UNRUN. Compatibility remains NOT ADOPTED, UNCOMPILED and UNRUN; fixed Record +ABI/accounting and one P3 parameter-list omission remain pending. No full CI or +readiness claim, no implied composition of overlapping UI and font-fix files. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/README.md b/proposals/render/2026-10-31/progressive-compatibility-wip/README.md new file mode 100644 index 000000000..df75e0a9c --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/README.md @@ -0,0 +1,65 @@ +# Progressive CPU: preserved compatibility WIP and isolated fixture fix + +31 October 2026. Source preservation for #6201; **local curation, not a production +source change or completed integration**. Four WIP subpackages retain 34 RAW +candidates, and a fifth package preserves the exact earlier compiled C28 host +reference: 35 source files total, with per-file RAW bindings and LF patches. +They are deliberately separate; this archive supplies no combined source. + +## Actual earlier C28 result, separate from these proposals + +The C28 source build succeeded with five library artifacts and ten inventories. +Of 983 selected cases, **28 passed, one failed and 954 were not run**; two actual +CPU-supported branch markers were observed before the stop. The failed case 976 +panicked because its separate UI test context had no ui-semibold font binding. +It did not reach a failing SPP/cap assertion. This is the earlier exact C28 result, +not a pass for the changed source packages below. + +The isolated one-line font fixture correction is preserved in fontfix and remains +UNRUN. It uses the actual bundled-font bootstrap already used by app and Harness, +with every original assertion intact. It is not a change to product typography. + +## Independent packages and required composition + +- [core](core/README.md): 26 source candidates for one serializable runtime cadence + authority, strict command handling, sparse legacy producer/host behavior and + eight written tests. Requires ui and prefs. +- [ui](ui/README.md): five source candidates for captured preference identity and + copy-only Interactive sampling, plus six neutral constructors and five tests. +- [prefs](prefs/README.md): two candidates, including the locale v2 successor; two + independent true-default bools and one preference-contract test. +- [fontfix](fontfix/README.md): one isolated existing-test fixture correction. +- [current-c28-host](current-c28-host/README.md): the exact formatted host from the + earlier C28 build, separate from the 34 uncompiled WIP candidates. Its recovery + preimage differs by exactly one LF; this file is not a complete build snapshot. + +All compatibility proposals are **NOT ADOPTED, UNCOMPILED and UNRUN**. Their 14 +new tests and the corrected existing test are not results. Exact later composition +must preserve both overlapping render_workspace_tests.rs deltas; neither full +candidate may replace the other. No hypothetical precedence is implied. + +The source has independent static Kernel and UI reviews. No demonstrated P1/P2 +functional defect was reported in those bounded reviews. One known P3 remains: +the earlier typed-job controls list at core/candidate/crates/engine/src/cmd/render.rs +line 127 omits cpu_progressive_every_pass although later documentation and the +parser admit it. The source bytes are preserved without silently fixing it. + +Actual Record layout/ABI and sufficient fixed admission accounting are pending. +An unchanged size assertion is not a measured layout or runtime pass. Resource +budgets must not be raised, and no allocation hidden, to satisfy these checks. + +No native application acceptance, full CI, renderer parity, first-launch policy +qualification, readiness or merge is claimed. BIN/native validation for the +earlier source remains a separate activity and is not blocked or replaced here. + +## How to review + +Each candidate is byte-identical to its closed owner packet; no formatter or +production edit was run by the curator. source-bindings.json in each directory +pins every RAW preimage and candidate. delta-LF-review.patch normalizes line endings +for reading; candidate bytes remain authoritative for mixed-EOL files. Do not apply +the archive to arbitrary main or qualify it using historical test results. + +Only public-safe source, portable bindings, review patches and these notes are +included. Private ledgers, scripts, grants, control receipts, logs, binaries and +local paths are excluded. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/README.md b/proposals/render/2026-10-31/progressive-compatibility-wip/core/README.md new file mode 100644 index 000000000..b3ddd3912 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/README.md @@ -0,0 +1,19 @@ +# Canonical request and producer compatibility WIP + +26 exact RAW candidates from the sealed W3 proposal. **NOT ADOPTED, UNCOMPILED, +UNRUN; not a complete workspace.** Eight new tests are written, not executed. +The sole runtime authority is ImageRequest.cpu_progressive_every_pass, with the +same strict top-level Start control: omitted/true keeps every-pass publication, +false survives serialization and restores the earlier sparse policy. Saved jobs +retain their own sampling authority. No skipped nested alias is introduced. + +The UI package supplies six required constructor updates and capture wiring; +prefs supplies two independent switches. Source reviews are not runtime proof. +The fixed Record embeds ImageRequest: actual target layout/ABI and sufficient +fixed admission accounting remain unqualified. Existing task/frame/metadata +assertions were preserved; their preservation is not a compiled PASS. + +Known P3: candidate crates/engine/src/cmd/render.rs:127 has an earlier saved-job +control list omitting cpu_progressive_every_pass; later parameter documentation +and the parser admit it. Correct that sentence during coordinated integration. +No demonstrated P1/P2 source defect was reported by the independent review. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/cmd/render.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/cmd/render.rs new file mode 100644 index 000000000..6a3dfb9b9 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/cmd/render.rs @@ -0,0 +1,441 @@ +//! Render capability discovery and persistent intent. No rendering or host probing. + +use std::sync::Arc; + +use serde::Deserialize; +use serde_json::{Value, json}; +use solidcraft_doc::render_settings::{RenderSettings, RenderSetup}; + +use super::CommandSpec; +use crate::params::bad; +use crate::{Result, Session}; + +mod clear_coat; +mod effects; +mod environment; +mod jobs; +mod library; +mod library_data; +#[cfg(test)] +mod light_union_tests; +mod lights; +mod optical_bindings; +mod physical_library; +mod resources; +mod shots; +mod staging; +mod studio_presets; +mod surface_bindings; +mod textures; +mod transmission; + +pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("render.environment.set", "Set Render Environment", crate::checked!("render.environment.set", environment::set)).icon("settings").doc_only() + .contract(&environment::CONTRACT) + .output(crate::schema::output_schema_for::) + .params("name; set?: numerical setup patch; rotation_deg?: finite degrees within +/-1000000, wrapped to [-180,180); intensity?: finite linear intensity 0..64 CPU or 0..100 GPU. Edits the existing HDR, sky or constant environment in one undo, without selecting a source, moving the camera or starting a render. Absent environments and raster refuse."), + CommandSpec::new("render.lights.set", "Set Render Light", crate::checked!("render.lights.set", lights::set)) + .icon("render_scene").doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, 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, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."), + CommandSpec::new("render.lights.add", "Add Light", crate::checked!("render.lights.add", lights::add)) + .icon("render_scene").doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, 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, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."), + CommandSpec::new("render.lights.duplicate", "Duplicate Render Light", crate::checked!("render.lights.duplicate", lights::duplicate)) + .icon("render_scene").doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, 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, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."), + CommandSpec::new("render.lights.remove", "Remove Render Light", crate::checked!("render.lights.remove", lights::remove)) + .icon("render_scene").doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("name; id except add; settings?: full unsaved RenderSetup; expected_revision?:u64; set for set/add: kind directional/point/spot/area, 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, minimum_distance_mm. Validated finite light edit in one undo. Existing family caps and backend support apply; refusal is atomic. Names remain defaults."), + CommandSpec::new("render.lights.list", "List Render Lights", crate::checked!("render.lights.list", lights::list)) + .icon("list").noundo().doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) + .params("setup?: saved setup name OR settings?: complete RenderSetup snapshot; neither uses defaults. Returns {lights:[{id,kind,name,name_key,number,implicit,intensity,colour,...spatial fields}]}. IDs are kind:zero-based-source-slot, stable across numerical edits but not family changes/reordering/removal/rig replacement; point and spot share punctual slots. Includes implicit default/preset lights. GPU RGB radiance is factored as colour * intensity; area edges are full world-mm vectors. Read-only, no host, camera change, save, render, model evaluation or undo. See docs/render-settings.md."), + CommandSpec::new("render.aging.describe","Layered Surface Aging",effects::aging).icon("appearance").noundo().doc_only() + .params("Empty object. Read-only original Rust/patina/dust/grime/scratch/chip/fading presets and exact GPU aging contract. UI activation opens the shared Aging tab; edits remain a saved render draft, never engineering geometry or material-property mutation."), + CommandSpec::new("render.effects.describe","Lens and Creative Effects",effects::presentation).icon("camera").noundo().doc_only() + .params("Empty object. Read-only original photographic/creative filter defaults and constraints. UI activation opens shared Effects controls. Saved finishing and exact-master regrading preserve raw EXR bytes; no physical lens or branded-film calibration is implied."), + CommandSpec::new("render.optics.bind","Save Optical Binding",optical_bindings::bind).icon("appearance") + .params("name: GPU setup; set?: complete numerical setup patch; body_index and body_name: exact captured target; expected_revision; optics:{ior,absorption_per_mm:[r,g,b],boundary:closed_mesh|closed_box|thin_sheet,thickness_mm,shadow_transmission,subsurface?:{scattering_per_mm,anisotropy}}; replace?:false. Stores stable definition/feature/occurrence identity in one undo without modifying engineering geometry/materials. Nested media require separate job.options.nested_media and producer certification. Unresolved or incompatible targets refuse atomically."), + CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only() + .params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."), + CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only() + .params("job: exact completed JobId; presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), + CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only() + .params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."), + CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo() + .params("No parameters. Returns the explicitly defined current view camera, or null if the session has no camera override. No camera is fitted, no job is started and no saved setup or engineering document is changed."), +CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon("camera").noundo() + .params("No parameters. Fits the current camera to the visible product bounds through the shared Camera::fit contract; changes only view state, not a saved setup, rendering job, stage or engineering geometry."), +CommandSpec::new("render.preset.resolve", "Review Native Studio", studio_presets::resolve).icon("render_scene").noundo() + .params("id: NATIVE-STUDIO-001..025; name; set?: typed GPU setup patch; expected_revision?:u64. Resolves original built-in HDR/rig/passive ground with conservative geometry clearance, returns all replacements and preserved fields without mutation. Unbound SCENE-* concepts are not accepted."), +CommandSpec::new("render.preset.apply", "Apply Native Studio", studio_presets::apply).icon("render_scene") + .params("Same reviewed input as render.preset.resolve, expected_revision required, replace_lighting_and_environment:true and replace_stage:true when an existing stage would change. Re-resolves the complete candidate and publishes one undo or no mutation; camera, optical bindings, geometry and engineering materials are preserved."), +CommandSpec::new("render.quality.prepare", "Review Fixed Sampling Budget", studio_presets::quality).icon("settings").noundo().doc_only() + .params("id: Q-*; variant:fixed_samples_png; acknowledge_omissions:true. Read-only bounded GPU still-budget projection, not full adaptive/convergence/linear-master quality acceptance. Returns dimensions/samples/depth/seed/denoise and explicit omissions. Never switches executor or mutates a shot."), +CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", shots::duplicate).icon("copy").doc_only() + .params("name, new_name, expected_revision:u64. Copies exact saved setup and resource references in one undo. Existing destinations refuse; captured jobs and camera navigation are unchanged."), +CommandSpec::new("render.shot.rename", "Rename Render Shot", shots::rename).icon("settings").doc_only() + .params("name, new_name, expected_revision:u64. Renames exact saved setup in one undo; an existing destination or stale review refuses."), +CommandSpec::new("render.shot.remove", "Remove Render Shot", shots::remove).icon("delete").doc_only() + .params("name, expected_revision:u64. Removes only that saved setup in one undo; retains resources, geometry and captured results."), +CommandSpec::new("render.library.preview", "Inspect Original Surface Map", library::preview).icon("appearance").noundo().doc_only() + .params("id: SURF-*. Returns bounded hash-verified original base-color PNG bytes and source-map fidelity label, not a rendered material thumbnail. No external paths, rendering or document edits."), +CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", physical_library::prepare).icon("inspect").noundo().doc_only() + .params("id: named built-in physical profile, name: proposed new material label, acknowledge_reference:true. Read-only loss-aware creation plan using native ValidatedCard admission and one point density; returns source receipts, extended fields and omissions. Does not execute material.create, assign bodies or infer effective-part physics."), +CommandSpec::new("render.stage.ground", "Save Render Ground", staging::ground).icon("render_scene") + .params("name: typed raytrace setup, set?: setup patch, margin_fraction?:0.25, gap_mm?:0.1, reflectance_linear?:[0.18,0.18,0.18], replace_stage?:false. Fits one finite passive ground below the visible product once and saves its physical transforms in one undo. Product AABB separation is rechecked on every render."), +CommandSpec::new("render.stage.backdrop", "Save Physical Render Background", staging::backdrop).icon("render_scene").doc_only() + .params("name: typed raytrace setup, set?: setup patch, kind: floor_wall or cyclorama, reflectance_linear?: [0.18,0.18,0.18], expected_revision: reviewed revision, replace_stage?:false. Fits a finite floor/wall or a 24-strip polygonal cyclorama behind the visible subject using the saved camera azimuth; world +Z up and a minimum one-mm stage envelope. Preserves subject geometry, lighting, output, pose and engineering materials; one undo and rechecked product separation. Not an infinite/analytically smooth/terrain background."), +CommandSpec::new("render.stage.clear", "Remove Render Stage", staging::clear).icon("render_scene").doc_only() + .params("name: setup, set?: setup patch. Removes saved render-only panels atomically; CAD geometry and lighting are unchanged."), +CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_bindings::bind).icon("appearance") + .params("name: GPU setup; set?: setup patch; surface: same input as render.library.surface.prepare; replace?: false. Pins exact source hashes and definition/feature/occurrence identity with local-mm mapping in one undo. No paths, mesh ordinals or physical material changes."), +CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only() + .params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."), + CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only() + .params("job: completed JobId, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), +CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo() + .params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."), +CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only() + .params("kind?: surfaces, selene_appearances, hdr, rigs, scenes, materials, lighting, environments, quality, native_scenes, selene_shots or capabilities; query?: bounded search; availability?: all/usable/specification/blocked; offset?:0; limit?:48 (1..128). Returns source status and explicit implemented projections separately. No device, file IO or design change."), +CommandSpec::new("render.library.describe", "Inspect Render Library Resource", library::describe).icon("inspect").noundo().doc_only() + .params("kind, id: exact authored resource. Returns original specification, runtime projection variants and explicit omissions. A concept is not an executable preset."), +CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appearance", library::apply_appearance).icon("appearance") + .params("id: SURF-* or SELENE-AP-*; variant: uniform_opaque (required); bodies: 1..256 exact body names. Applies the original scalar baseline through ordinary appearance assignment in one undo, preserving physical properties. Spatial maps and advanced target effects are explicitly excluded."), +CommandSpec::new("render.library.environment.apply", "Apply Built-in HDR Environment", library::apply_environment).icon("settings").doc_only() + .params("id: HDR-*; name: saved setup; set?: typed CPU/GPU setup patch; rotation_rad?: authored rotation (native origin offset is explicit in the reply); intensity?:1; samples?:16 for CPU; replace_environment?:false. Hash-verifies and embeds original bytes, saves one atomic undo without external files or a render device. An HDR-owned sun cannot duplicate an analytic sun."), +CommandSpec::new("render.library.surface.prepare", "Prepare Authored Surface Maps", library::prepare_surface).icon("appearance").noundo() + .params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1. Returns an explicit GPU planar map binding with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."), +CommandSpec::new("render.library.studio.prepare", "Prepare Authored Studio Lights", library::prepare_studio).icon("inspect").noundo().doc_only() + .params("id: RIG-*; variant: complete for emitter-only rigs, emitters_only for rigs with passive cards; center_mm and subject_extent_mm required. Converts exact rectangular half-edges and solar direction/radius to GPU lighting. Blocked calibration and external-sun rigs refuse. Returns a geometry-clearance review requirement; does not create cards or modify the scene."), +CommandSpec::new("render.library.studio.apply", "Apply Authored Studio Lights", library::apply_studio).icon("settings") + .params("rig: render.library.studio.prepare parameters; name; set?: typed GPU setup patch; replace_lighting_and_environment:true required. Saves the explicit rig projection in one undo, removing prior lighting/environment only with that confirmation. Subject clearance still needs review; passive cards are never silently omitted."), +CommandSpec::new("render.hdr.inspect", "Inspect HDR Source", resources::inspect).icon("inspect").noundo().doc_only() + .params("path: scoped Radiance HDR file; validates the complete bounded source and returns sha256, width, height, encoded_bytes and primaries without saving or rendering"), +CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", resources::capture_settings).icon("settings").doc_only() + .params("name, set: typed CPU/GPU setup patch with hdr/environment unset; path: scoped HDR; expected_sha256?: digest returned by render.hdr.inspect (changed sources refuse); rotation_rad?:0, intensity?:1; samples?:1/4/16/64 for CPU only (default16); assume_linear_srgb?:false for GPU only. Captures immutable bytes and saves resource plus setup atomically in one undo, without a host; returns name/setup/resource metadata, never source bytes"), +CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only() + .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace, transient studio_weights, raster_lights and progressive_feedback may accompany it. raster_lights?: transient null (legacy studio) or 0..8 directional sources {direction:[x,y,z],color:[linear r,g,b],intensity:0..64}; empty array is dark direct lighting. Requires builtin Raster without studio_weights, raytrace, HDR, transmission or other method controls; existing RenderSetup.exposure_ev is captured for Raster within -32..32. Directions are finite/nonzero and bounded by 1e9; RGB is 0..1. Not saved; no shadows or physical glass. raster_punctual_lights?: transient null or 0..8 shared point/spot sources {position_mm:[x,y,z],color:[linear r,g,b],intensity:0..64,reference_distance_mm:0.001..1000000,minimum_distance_mm:0.001..reference_distance_mm,cone?:{emitted_axis:[x,y,z],inner_half_angle_radians,outer_half_angle_radians}}. Spot angles require 0<=inner Result { + let cmd = "render.camera.set"; + if !params.as_object().is_some_and(|p| p.len() == 1 && p.contains_key("camera")) { + return Err(bad(cmd, "expected exactly one camera snapshot")); + } + // Reuse strict saved-camera decoding and its numeric limits, without saving a setup. + let setup: RenderSetup = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?; + setup.validate().map_err(|e| bad(cmd, e.to_string()))?; + s.camera = Some(setup.camera); + Ok(json!({"camera":setup.camera,"document_changed":false})) +} + +fn get_camera(s: &mut Session, params: &Value) -> Result { + if !params.as_object().is_some_and(|p| p.is_empty()) { + return Err(bad("render.camera.get", "expected an empty parameter object")); + } + Ok(json!({"camera":s.camera,"explicit_view":s.camera.is_some(),"document_changed":false})) +} + +fn fit_camera(s: &mut Session, params: &Value) -> Result { + if !params.as_object().is_some_and(|p| p.is_empty()) { + return Err(bad("render.camera.fit", "expected an empty parameter object")); + } + let scene = crate::product_scene::extract(s)?; + let mut camera = s.camera.unwrap_or_default(); + if !scene.bounds.is_empty() { + camera.fit(&scene.bounds); + } + s.camera = Some(camera); + Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false})) +} + +fn scene(s: &mut Session, params: &Value) -> Result { + if !params.as_object().is_some_and(|p| p.is_empty()) { + return Err(bad("render.scene", "expected an empty parameter object")); + } + let scene = crate::product_scene::extract(s)?; + let mut stable = std::collections::BTreeMap::new(); + for (target, name) in surface_bindings::targets(s, "render.scene")? { + if stable.insert(name, target).is_some() { + return Err(bad("render.scene", "ambiguous stable occurrence name")); + } + } + let bodies: Vec<_> = scene + .meshes + .iter() + .enumerate() + .map(|(ordinal,m)| json!({"ordinal":ordinal,"name":m.name,"stable_target":stable.get(&m.name),"triangles":m.mesh.triangles.len(),"color":m.color,"opacity":m.opacity,"face_appearances":m.faces.len(),"bounds":{"min":m.mesh.bounds().min,"max":m.mesh.bounds().max}})) + .collect(); + Ok( + json!({"bodies":bodies,"bounds":if scene.bounds.is_empty() { Value::Null } else { json!({"min":scene.bounds.min,"max":scene.bounds.max}) },"overlays":false}), + ) +} + +fn apply_settings(s: &mut Session, params: &Value) -> Result { + let request: GetSettings = serde_json::from_value(params.clone()).map_err(|e| bad("render.settings.apply", e.to_string()))?; + let name = request.name.ok_or_else(|| bad("render.settings.apply", "`name` is required"))?; + RenderSettings::validate_name(&name).map_err(|e| bad("render.settings.apply", e.to_string()))?; + let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad("render.settings.apply", "no saved render setup with that name"))?; + setup.validate().map_err(|e| bad("render.settings.apply", e.to_string()))?; + s.camera = Some(setup.camera); + Ok(json!({"name":name,"camera":setup.camera})) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct GetSettings { + name: Option, +} + +fn get_settings(s: &mut Session, params: &Value) -> Result { + let cmd = "render.settings.get"; + let request: GetSettings = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?; + match request.name { + None => Ok(json!({"setups": s.doc.render.setups, "defaults": RenderSetup::default()})), + Some(name) => { + RenderSettings::validate_name(&name).map_err(|e| bad(cmd, e.to_string()))?; + let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad(cmd, "no saved render setup with that name"))?; + Ok(json!({"name": name, "setup": setup})) + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SetSettings { + name: String, + set: Value, +} + +fn set_settings(s: &mut Session, params: &Value) -> Result { + let cmd = "render.settings.set"; + if let Some(set) = params.get("set") { + validate_saved_raster_lights(set, cmd)?; + } + let request: SetSettings = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?; + let setup = patched_settings(s, &request.name, &request.set, cmd)?; + let reply = json!({"name": request.name, "setup": setup}); + if s.doc.render.setups.get(&request.name) == Some(&setup) { + return Ok(reply); + } + let mut settings = (*s.doc.render).clone(); + settings.setups.insert(request.name, setup); + settings.validate().map_err(|e| bad(cmd, e.to_string()))?; + s.doc_mut().render = Arc::new(settings); + Ok(reply) +} + +fn patched_settings(s: &Session, name: &str, set: &Value, cmd: &str) -> Result { + validate_saved_raster_lights(set, cmd)?; + RenderSettings::validate_name(name).map_err(|e| bad(cmd, e.to_string()))?; + let patch = set.as_object().filter(|p| p.len() <= 13).ok_or_else(|| bad(cmd, "`set` must be an object with at most 13 fields"))?; + if let Some(current) = s.doc.render.setups.get(name) + && let Some(solidcraft_doc::render_settings::RenderJob::Raster { lights, .. }) = ¤t.job + { + solidcraft_render::job::validate_raster_lights(lights).map_err(|e| bad(cmd, e.to_string()))?; + } + let current = s.doc.render.setups.get(name).cloned().unwrap_or_default(); + let mut value = serde_json::to_value(¤t).map_err(|e| bad(cmd, e.to_string()))?; + let object = value.as_object_mut().ok_or_else(|| bad(cmd, "invalid render setup"))?; + for (key, value) in patch { + object.insert(key.clone(), value.clone()); + } + let setup: RenderSetup = serde_json::from_value(value).map_err(|e| bad(cmd, e.to_string()))?; + setup.validate().map_err(|e| bad(cmd, e.to_string()))?; + Ok(setup) +} + +/// The new saved array is checked by reference before raw Value patch copies. +fn validate_saved_raster_lights(settings: &Value, command: &str) -> Result<()> { + if let Some(lights) = settings.get("job").and_then(|job| job.get("lights")) { + let _ = solidcraft_render::job::deserialize_raster_lights(lights).map_err(|e| bad(command, e.to_string()))?; + } + Ok(()) +} + +fn backends(s: &mut Session, params: &Value) -> Result { + if !params.as_object().is_some_and(|p| p.is_empty()) { + return Err(bad("render.backends", "expected an empty parameter object")); + } + Ok(json!({"schema_version": 1, "default_backend": "builtin", "backends": [s.render_backend()], + "cpu_resource_profiles": solidcraft_render::job::CpuBudget::ALL.map(|budget| json!({"id":budget,"limits":budget.limits()}))})) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + fn assert_unchanged(s: &mut Session, params: Value) -> Result { + let doc = s.doc.clone(); + let before = (s.is_dirty(), s.revision, s.evaluations, s.model.is_stale()); + let camera = s.camera; + let undo = s.undo.clone(); + let redo = s.redo.clone(); + let result = s.execute("render.backends", ¶ms); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert_eq!(before, (s.is_dirty(), s.revision, s.evaluations, s.model.is_stale())); + assert_eq!(camera, s.camera); + for (before, after) in [(&undo, &s.undo), (&redo, &s.redo)] { + assert_eq!(before.len(), after.len()); + for (a, b) in before.iter().zip(after.iter()) { + assert!(Arc::ptr_eq(&a.doc, &b.doc)); + assert_eq!((&a.label, a.active_sketch, &a.pending_moves), (&b.label, b.active_sketch, &b.pending_moves)); + } + } + result + } + + #[test] + fn discovery_preserves_clean_dirty_and_undo_redo_state() { + let mut s = Session::default(); + let r = assert_unchanged(&mut s, Value::Null).unwrap(); + assert_eq!(r["schema_version"], 1); + assert_eq!(r["default_backend"], "builtin"); + assert_eq!(r["backends"].as_array().unwrap().len(), 1); + let descriptor: crate::render::BackendDescriptor = serde_json::from_value(r["backends"][0].clone()).unwrap(); + assert_eq!(descriptor, crate::render::builtin_backend()); + s.execute("solid.box", &json!({"length": 10, "width": 20, "height": 5})).unwrap(); + s.execute("view.apply", &json!({"view": "top"})).unwrap(); + assert!(s.is_dirty()); + assert_unchanged(&mut s, json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.redo.is_empty()); + assert_unchanged(&mut s, json!({})).unwrap(); + for p in [json!([]), json!(3), json!({"backend": "missing"}), json!({"width": "bad"})] { + assert!(assert_unchanged(&mut s, p).is_err()); + } + } + + #[test] + fn cooperative_host_never_discovers_cpu_raytracing_or_accepts_its_reserved_viewport_id() { + use solidcraft_render::job::CpuHost; + let mut s = Session::default(); + s.set_render_job_host(Some(CpuHost::cooperative())).unwrap(); + let reply = assert_unchanged(&mut s, json!({})).unwrap(); + let backend: solidcraft_render::BackendDescriptor = serde_json::from_value(reply["backends"][0].clone()).unwrap(); + assert!(backend.executors.iter().any(|d| d.id.as_str() == "cpu-product")); + assert!(!backend.executors.iter().any(|d| d.id.as_str() == "cpu-raytrace")); + let mut viewport = CpuHost::cooperative().descriptor().unwrap(); + viewport.id = solidcraft_render::ExecutorId::new("cpu-raytrace").unwrap(); + viewport.profiles[0].operation = solidcraft_render::RenderOperation::Viewport; + viewport.profiles[0].formats.clear(); + assert!(s.set_render_viewport(Some(viewport)).unwrap_err().to_string().contains("reserved")); + assert_eq!(s.render_backend(), backend); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_discovery_matches_installed_features_and_preserves_raster_default() { + use solidcraft_render::job::{CpuHost, Integrator}; + use solidcraft_render::{RenderFeature, RenderFormat, RenderMode, RenderOperation, RenderRequest}; + let host = CpuHost::for_platform().unwrap(); + // Query the host so the same test covers feature-off builds and workspace + // feature unification without assuming the engine's own cfg is sufficient. + let raytrace = host.validate_integrator(Integrator::Raytrace).is_ok(); + let mut s = Session::default(); + let doc = s.doc.clone(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let reply = assert_unchanged(&mut s, json!({})).unwrap(); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert!(!s.is_dirty()); + assert!(s.undo.is_empty()); + let backend: solidcraft_render::BackendDescriptor = serde_json::from_value(reply["backends"][0].clone()).unwrap(); + let descriptors: Vec<_> = backend.executors.iter().filter(|d| d.id.as_str() == "cpu-raytrace").collect(); + assert_eq!(descriptors.len(), usize::from(raytrace)); + if let Some(descriptor) = descriptors.first() { + assert_eq!(descriptor.availability, solidcraft_render::Availability::Available); + assert_eq!(*descriptor, &host.descriptor_for(Integrator::Raytrace).unwrap()); + assert!(!descriptor.profiles.iter().any(|p| p.features.contains(&RenderFeature::Progressive))); + } + let request = RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: 16, + height: 16, + format: Some(RenderFormat::Png), + features: vec![RenderFeature::Pbr], + policy: Default::default(), + }; + assert_eq!(solidcraft_render::resolve_request(std::slice::from_ref(&backend), &request).unwrap().executor.as_str(), "cpu-product"); + assert_eq!(s.scratch().render_backend(), backend); + s.set_render_job_host(Some(host)).unwrap(); + assert_eq!(s.render_backend(), backend, "reinstalling the same host cannot duplicate method descriptors"); + s.set_render_job_host(Some(CpuHost::cooperative())).unwrap(); + assert!(!s.render_backend().executors.iter().any(|d| d.id.as_str() == "cpu-raytrace")); + s.set_render_job_host(None).unwrap(); + assert_eq!(s.render_backend(), solidcraft_render::builtin_backend()); + assert_unchanged(&mut s, json!({})).unwrap(); + assert!(Arc::ptr_eq(&doc, &s.doc)); + assert!(!s.is_dirty()); + assert!(s.undo.is_empty()); + } + + #[test] + fn discovery_does_not_settle_a_live_drag_or_rebuild_geometry() { + let mut s = Session::default(); + for (id, p) in [ + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [25, 20]})), + ("sketch.dimension", json!({"entities": ["l1"], "value": 20})), + ("sketch.dimension", json!({"entities": ["l2"], "value": 15})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance": 5})), + ("sketch.edit", json!({"sketch": "Sketch1"})), + ("sketch.drag", json!({"entity": "l1.start", "from": [5, 5], "to": [4, 5], "live": true})), + ] { + s.execute(id, &p).unwrap(); + } + assert!(s.model.is_stale()); + s.evaluations = 0; + let model = s.model.state(); + assert_unchanged(&mut s, json!({})).unwrap(); + assert_unchanged(&mut s, json!({"unexpected": true})).unwrap_err(); + assert!(Arc::ptr_eq(&model, &s.model.state())); + assert_eq!(s.evaluations, 0); + } +} + +#[cfg(test)] +mod settings_tests; + +#[cfg(test)] +mod job_tests; + +pub(super) fn prepare_interactive(s: &crate::Session, params: &serde_json::Value) -> crate::Result { + jobs::interactive(s, params) +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/cmd/render/jobs.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/cmd/render/jobs.rs new file mode 100644 index 000000000..afa55fd04 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/cmd/render/jobs.rs @@ -0,0 +1,1622 @@ +use crate::{Result, Session, params::bad, render_jobs::job_error}; +use serde::Deserialize; +use serde_json::{Value, json}; +use solidcraft_doc::render_resources::{CpuHdrEnvironment, GpuHdrEnvironment}; +use solidcraft_doc::render_settings::{RenderJob, RenderSetup}; +use solidcraft_render::{ + RenderOperation, RenderRequest, + job::{ImageRequest, Integrator, JobId, RaytraceOptions}, +}; + +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct Start { + #[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_lights")] + raster_lights: Option>, + #[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_punctual_lights")] + raster_punctual_lights: Option>, + #[serde(default, deserialize_with = "solidcraft_render::job::deserialize_raster_area_lights")] + raster_area_lights: Option>, + progressive_feedback: bool, + #[serde(default, deserialize_with = "cpu_progressive_every_pass_input")] + cpu_progressive_every_pass: Option, + nested_media: bool, + studio_weights: Option<[f64; 3]>, + progressive: bool, + denoise: bool, + samples: Option, + max_depth: Option, + seed: Option, + integrator: Integrator, + environment: Option, + raytrace: Option, + led_strip: Option, + led_samples: Option, + setup: Option, + settings: Option, + transparent_background: bool, + replace: bool, +} + +// Omission is allowed; an explicitly supplied null/string/number is not a bool. +fn cpu_progressive_every_pass_input<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result, D::Error> { + bool::deserialize(deserializer).map(Some) +} + +#[derive(Deserialize)] +#[serde(default, deny_unknown_fields)] +struct EnvironmentRequest { + path: String, + resource: Option, + expected_sha256: Option, + rotation_radians: f64, + intensity: f64, + samples: u32, +} +impl Default for EnvironmentRequest { + fn default() -> Self { + Self { path: String::new(), resource: None, expected_sha256: None, rotation_radians: 0.0, intensity: 1.0, samples: 16 } + } +} + +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct ProgressiveStart { + progressive_feedback: bool, + studio_weights: Option<[f64; 3]>, + aging: solidcraft_doc::render_aging::SavedAgingStack, + #[serde(default)] + nested_media: bool, + volume: Option, + adaptive: Option, + transmission_samples: Option, + finishing: solidcraft_render::job::finishing::Finishing, + backdrop: Option, + linear_exr: bool, + integrator: Integrator, + setup: Option, + settings: Option, + transparent_background: bool, + replace: bool, + progressive: bool, + samples: Option, + max_depth: Option, + seed: Option, + raytrace: super::transmission::Raytrace, + lens: Option, + lighting: Option, + tone_map: Option, + environment: Option, + denoise: bool, +} + +struct Prepared { + progressive_feedback: bool, + replace: bool, + scene: solidcraft_render::ProductScene, + request: ImageRequest, + reply: Value, + executor: solidcraft_render::ExecutorId, + options: solidcraft_render::job::JobOptions, + environment: Option, +} + +fn lower_led(input: &mut Start, command: &str) -> Result<()> { + if input.led_strip.is_none() && input.led_samples.is_some() { + return Err(bad(command, "led_samples requires led_strip")); + } + if let Some(strip) = input.led_strip { + if input.integrator != Integrator::Raytrace { + return Err(bad(command, "led_strip requires integrator: raytrace")); + } + strip.append_to(input.raytrace.get_or_insert_default(), input.led_samples.unwrap_or(16)).map_err(job_error)?; + input.led_strip = None; + input.led_samples = None; + } + Ok(()) +} + +/// Pure preview lowering. Parse the existing CPU wire before changing its sampling; +/// unsupported effects remain errors rather than disappearing from the request. +fn interactive_params(params: &Value) -> Result { + let command = "render.interactive"; + let mut input = Start::deserialize(params).map_err(|e| bad(command, e.to_string()))?; + let object = params.as_object().ok_or_else(|| bad(command, "Interactive requires an explicit CPU request object"))?; + if object.contains_key("setup") || object.contains_key("replace") { + return Err(bad(command, "Interactive requires an explicit settings snapshot without setup or replace")); + } + if input.raster_lights.is_some() || input.raster_punctual_lights.is_some() || input.raster_area_lights.is_some() { + return Err(bad(command, "Interactive does not accept explicit Raster lights")); + } + if input.integrator != Integrator::Raytrace || input.progressive || input.transparent_background { + return Err(bad(command, "Interactive requires opaque CPU ray tracing, not GPU progressive or raster rendering")); + } + if input.studio_weights.is_some() || input.denoise || input.samples.is_some() || input.max_depth.is_some() || input.seed.is_some() { + return Err(bad(command, "Interactive cannot accept GPU studio, denoise or sampling controls")); + } + let mut settings = input.settings.take().ok_or_else(|| bad(command, "Interactive requires explicit settings"))?; + if settings.job.is_some() { + return Err(bad(command, "Interactive requires a lowered CPU runtime request with settings.job: null")); + } + if settings.mode != solidcraft_render::RenderMode::Preview || settings.format != solidcraft_render::RenderFormat::Png { + return Err(bad(command, "Interactive CPU requires the existing Preview/Image/PNG profile")); + } + // Keep the existing CPU runtime exposure authority; never silently neutralize + // saved/common controls in order to make a request acceptable. + if settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 { + return Err(bad(command, "Interactive CPU exposure belongs to raytrace.exposure_ev; environment controls belong to the captured input")); + } + lower_led(&mut input, command)?; + if let Some(environment) = &input.environment { + // Same numerical controls as EnvironmentInput::new, checked before a path + // can be read. Resource bytes and primaries remain prepare's responsibility. + if !environment.rotation_radians.is_finite() + || !environment.intensity.is_finite() + || !(0.0..=64.0).contains(&environment.intensity) + || !matches!(environment.samples, 1 | 4 | 16 | 64) + { + return Err(bad(command, "invalid Interactive environment controls")); + } + if input.raytrace.as_ref().is_some_and(|options| options.environment.is_some()) { + return Err(bad(command, "choose either captured HDR or constant CPU environment")); + } + } + let final_request = ImageRequest { + cpu_progressive_every_pass: input.cpu_progressive_every_pass.unwrap_or(true), + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + camera: settings.camera, + width: settings.width, + height: settings.height, + background: settings.background, + transparent_background: input.transparent_background, + integrator: input.integrator, + raytrace: input.raytrace, + studio_weights: input.studio_weights, + environment: None, + textures: None, + }; + let preview = solidcraft_render::job::interactive::cpu_request(&final_request).map_err(job_error)?; + settings.width = preview.width; + settings.height = preview.height; + let budget = preview.raytrace.as_ref().map_or(solidcraft_render::job::CpuBudget::Compact, |options| options.budget); + settings.validate_for_cpu(budget).map_err(|e| bad(command, e.to_string()))?; + // Preserve every original field after strict deserialization. Only the LED + // recipe has been consumed into real area lights; do not lower it twice. + let mut lowered = object.clone(); + lowered.remove("led_strip"); + lowered.remove("led_samples"); + lowered.insert("settings".into(), serde_json::to_value(settings).map_err(|e| bad(command, e.to_string()))?); + lowered.insert("raytrace".into(), serde_json::to_value(preview.raytrace).map_err(|e| bad(command, e.to_string()))?); + Ok(Value::Object(lowered)) +} + +/// Capture/admit only. The engine's Interactive owner submits outside the final +/// registry; this helper never starts, replaces, cancels or exports a job. +pub(super) fn interactive(s: &Session, params: &Value) -> Result { + let params = interactive_params(params)?; + let prepared = prepare(s, ¶ms, "render.interactive")?; + if prepared.executor.as_str() != "cpu-raytrace" { + return Err(bad("render.interactive", "Interactive requires the installed cpu-raytrace executor")); + } + Ok(crate::render_interactive::Prepared { + scene: prepared.scene, + request: prepared.request, + options: prepared.options, + environment: prepared.environment, + }) +} + +#[cfg(test)] +mod union_lowering_tests { + #[test] + fn cpu_cadence_wire_rejects_null_nonbool_and_nonprogressive_controls_before_capture() { + let mut wire = json!({"cpu_progressive_every_pass":false}); + assert_eq!(Start::deserialize(&wire).unwrap().cpu_progressive_every_pass, Some(false)); + assert_eq!(Start::deserialize(&json!({})).unwrap().cpu_progressive_every_pass, None); + for invalid in [Value::Null, json!(0), json!("false"), json!([]), json!({})] { + wire["cpu_progressive_every_pass"] = invalid; + assert!(Start::deserialize(&wire).is_err()); + } + for params in [ + json!({"cpu_progressive_every_pass":false}), + json!({"cpu_progressive_every_pass":true,"integrator":"raytrace","raytrace":{}}), + json!({"cpu_progressive_every_pass":false,"progressive":true}), + ] { + let error = prepare(&Session::default(), ¶ms, "render.preflight").err().unwrap().to_string(); + assert!(error.contains("cpu_progressive_every_pass requires CPU progressive raytracing"), "{error}"); + } + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn saved_cpu_cadence_command_replay_normalizes_false_and_keeps_it_through_the_native_worker() { + let mut session = Session::default(); + let host = solidcraft_render::job::CpuHost::for_platform().unwrap(); + session.set_render_job_host(Some(host)).unwrap(); + let document = session.doc.to_json(); + let original = json!({"settings":{"width":4,"height":3,"background":[17,31,59], + "job":{"method":"cpu_raytrace","options":{"lights":[],"shadows":false,"progressive":{"samples_per_pixel":5,"seed":97}}}}, + "cpu_progressive_every_pass":false}); + let replay: Value = serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap(); + assert_eq!(replay, original); + let normalized = normalize_saved_job(&session, &replay, "render.start").unwrap().unwrap(); + assert_eq!(normalized.params["cpu_progressive_every_pass"], false); + assert!(normalized.params["settings"]["job"].is_null()); + let prepared = prepare(&session, &replay, "render.preflight").unwrap(); + assert!(!prepared.request.cpu_progressive_every_pass); + assert_eq!(prepared.reply["request"]["cpu_progressive_every_pass"], false); + let decoded: ImageRequest = serde_json::from_value(prepared.reply["request"].clone()).unwrap(); + assert!(!decoded.cpu_progressive_every_pass); + assert_eq!(decoded.raytrace.as_ref().unwrap().progressive.unwrap().seed, 97); + let mut reference: Option> = None; + for every_pass in [false, true] { + let mut params = replay.clone(); + params["cpu_progressive_every_pass"] = json!(every_pass); + let started = start(&mut session, ¶ms).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(20)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed); + assert_eq!(status.request.cpu_progressive_every_pass, every_pass); + let status_wire = serde_json::to_value(&status).unwrap(); + assert_eq!(status_wire["request"].get("cpu_progressive_every_pass"), (!every_pass).then_some(&Value::Bool(false))); + let frame = handle.frame().unwrap().unwrap(); + if let Some(expected) = &reference { + assert_eq!(frame.png(), expected.as_slice()); + } else { + reference = Some(frame.png().to_vec()); + } + } + assert_eq!(session.doc.to_json(), document, "runtime cadence cannot become saved document intent"); + } + + + + #[cfg(not(target_arch = "wasm32"))] + fn raster_local_command_fixture() -> (Session, Value) { + let mut s = Session::default(); + s.execute( + "solid.box", + &json!({"length":20,"width":20,"height":4,"center":[0,0,0],"operation":"new","body_name":"Raster local command fixture"}), + ) + .unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::for_platform().unwrap())).unwrap(); + let mut camera = solidcraft_render::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(solidcraft_render::StandardView::Top); + let wire = json!({"settings":{"width":8,"height":8,"camera":camera,"background":[20,40,60],"exposure_ev":1.25,"job":null}, + "raster_punctual_lights":[{"position_mm":[0.0,0.0,20.0],"color":[0.25,0.5,1.0],"intensity":2.0,"reference_distance_mm":20.0,"minimum_distance_mm":0.001}], + "raster_area_lights":[{"center_mm":[0.0,0.0,20.0],"edge_u_mm":[4.0,0.0,0.0],"edge_v_mm":[0.0,-4.0,0.0],"color":[1.0,0.5,0.25],"intensity":2.0}]}); + (s, wire) + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn raster_local_public_preflight_start_status_and_real_png_keep_both_sources_and_one_ev() { + use solidcraft_render::job::{JobId, Phase}; + let (mut s, wire) = raster_local_command_fixture(); + let original = wire.clone(); + let checked = s.execute("render.preflight", &wire).unwrap(); + assert_eq!(checked["request"]["raster_punctual_lights"], wire["raster_punctual_lights"]); + assert_eq!(checked["request"]["raster_area_lights"], wire["raster_area_lights"]); + assert_eq!(checked["request"]["raster_exposure_ev"], 1.25); + assert!(checked["request"].get("raster_lights").is_none(), "no implicit directionals added"); + let started = s.execute("render.start", &wire).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.request.raster_exposure_ev, 1.25); + assert_eq!(serde_json::to_value(&status.request.raster_punctual_lights).unwrap(), wire["raster_punctual_lights"]); + assert_eq!(serde_json::to_value(&status.request.raster_area_lights).unwrap(), wire["raster_area_lights"]); + let frame = handle.frame().unwrap().unwrap(); + let bright = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(bright.dimensions(), (8, 8)); + let mut empty = wire.clone(); + empty["raster_punctual_lights"] = json!([]); + empty["raster_area_lights"] = json!([]); + let started = s.execute("render.start", &empty).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let dark_handle = s.render_job_handle(id).unwrap(); + assert_eq!(dark_handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let dark_frame = dark_handle.frame().unwrap().unwrap(); + let dark = image::load_from_memory(dark_frame.png()).unwrap().to_rgba8(); + assert_ne!(bright, dark, "actual local lights must change the real producer output"); + assert_eq!(wire, original, "input intent is immutable"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn raster_local_public_commands_refuse_saved_and_foreign_controls_without_reservation() { + let (mut s, wire) = raster_local_command_fixture(); + let before_revision = s.revision; + let mut saved = wire.clone(); + saved["settings"]["job"] = serde_json::to_value(RenderJob::Raster { transparent_background: false, lights: None }).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &saved).unwrap_err().to_string(); + assert!(error.contains("saved local-light authoring"), "{error}"); + } + for (key, value) in [ + ("integrator", json!("raytrace")), + ("studio_weights", json!([1, 1, 1])), + ("raytrace", json!({})), + ("environment", json!({"path":"must-not-be-opened.hdr"})), + ("nested_media", json!(true)), + ("progressive_feedback", json!(true)), + ("progressive", json!(true)), + ("samples", json!(1)), + ("seed", json!(0)), + ("denoise", json!(true)), + ] { + let mut invalid = wire.clone(); + invalid[key] = value; + for command in ["render.preflight", "render.start"] { + assert!(s.execute(command, &invalid).is_err(), "{command} accepted {key}"); + assert_eq!(s.render_job_host().unwrap().admitted_bytes(), 0, "no failed request reserved work"); + } + } + let mut interactive = wire; + interactive["integrator"] = json!("raytrace"); + assert!(interactive_params(&interactive).is_err()); + assert_eq!(s.revision, before_revision); + } + + #[test] + fn raster_local_public_command_caps_refuse_before_host_lookup_or_scene_capture() { + let point = json!({"position_mm":[0,0,20],"color":[1,1,1],"intensity":1,"reference_distance_mm":20,"minimum_distance_mm":0.001}); + let area = json!({"center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,-4,0],"color":[1,1,1],"intensity":1}); + let mut s = Session::default(); + for (key, value, reason) in + [("raster_punctual_lights", json!(vec![point; 9]), "at most eight"), ("raster_area_lights", json!(vec![area; 5]), "at most four")] + { + let mut wire = json!({}); + wire[key] = value; + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &wire).unwrap_err().to_string(); + assert!(error.contains(reason), "bound must fail before absent host: {error}"); + } + } + } + + use super::*; + #[test] + fn led_lowering_keeps_hdr_reflection_aa_and_anisotropy_inputs_without_reading_hdr() { + let wire = json!({"integrator":"raytrace","environment":{"path":"unopened.hdr","rotation_radians":0.75,"intensity":2,"samples":64},"raytrace":{"primary_samples":4,"reflections":{"bodies":[{"body":"receiver","mode":"rough_specular"}],"samples":16,"max_bounces":3},"anisotropic_faces":[{"body_index":0,"body_name":"receiver","face":0,"tangent":[1,0,0],"orientation":"quarter_turn","roughness_x":0.2,"roughness_y":0.5},null],"punctual_lights":[{"position_mm":[0,0,20],"color":[1,1,1],"intensity":1,"reference_distance_mm":20,"minimum_distance_mm":0.001}]},"led_strip":{"center_mm":[0,0,10],"length_mm":8,"width_mm":0.5,"length_axis":[1,0,0],"width_axis":[0,-1,0],"color":[1,0.5,0.25],"intensity":2},"led_samples":64}); + let mut input: Start = serde_json::from_value(wire.clone()).unwrap(); + let before = input.raytrace.clone().unwrap(); + lower_led(&mut input, "render.preflight").unwrap(); + let after = input.raytrace.unwrap(); + assert_eq!(before.primary_samples, after.primary_samples); + assert_eq!(before.reflections, after.reflections); + assert_eq!(before.anisotropic_faces, after.anisotropic_faces); + assert_eq!(before.punctual_lights, after.punctual_lights); + assert_eq!(after.area_lights.as_ref().unwrap().len(), 1); + assert_eq!(after.area_samples, Some(64)); + let environment = input.environment.unwrap(); + assert_eq!(environment.path, "unopened.hdr"); + assert_eq!(environment.rotation_radians, 0.75); + assert_eq!(environment.intensity, 2.0); + assert_eq!(environment.samples, 64); + assert!(input.led_strip.is_none() && input.led_samples.is_none()); + assert_eq!(wire["environment"]["path"], json!("unopened.hdr")); + } + fn interactive_final_wire() -> Value { + let camera = solidcraft_render::Camera { fov: 0.8, ..Default::default() }; + json!({"integrator":"raytrace","settings":{ + "width":3840,"height":2160,"camera":camera,"background":[20,40,60],"job":null, + "stage":[{"id":"floor","center_mm":[0.0,0.0,-5.0],"half_u_mm":[40.0,0.0,0.0], + "half_v_mm":[0.0,40.0,0.0],"reflectance_linear":[0.1,0.2,0.3]}]}, + "raytrace":{"primary_samples":4,"shadows":false,"exposure_ev":1.25,"lights":[], + "reflections":{"bodies":[{"body":"receiver","mode":"mirror"}],"samples":16,"max_bounces":3}, + "punctual_lights":[{"position_mm":[0.0,0.0,20.0],"color":[1.0,0.5,0.25],"intensity":2.0, + "reference_distance_mm":20.0,"minimum_distance_mm":0.01}], + "emissions":[{"body_index":0,"body":"receiver","color":[0.2,0.4,0.8],"strength":3.0}], + "surface_effects":[{"body":"receiver","repeat_mm":[2.0,3.0,4.0],"roughness_amplitude":0.1,"bump_amplitude_mm":0.01}]}, + "environment":{"path":"unopened-original.hdr","expected_sha256":"a".repeat(64), + "rotation_radians":0.75,"intensity":2.0,"samples":16}}) + } + + #[test] + fn interactive_fits_4k_before_admission_and_preserves_final_wire_and_transport() { + let wire = interactive_final_wire(); + let original = wire.clone(); + let lowered = interactive_params(&wire).unwrap(); + let before: Start = serde_json::from_value(wire.clone()).unwrap(); + let after: Start = serde_json::from_value(lowered.clone()).unwrap(); + let final_settings = before.settings.unwrap(); + let preview_settings = after.settings.unwrap(); + assert_eq!((final_settings.width, final_settings.height), (3840, 2160)); + assert_eq!((preview_settings.width, preview_settings.height), (1024, 576)); + assert!(before.raytrace.as_ref().unwrap().budget.validate_image(3840, 2160, None).is_err(), "Compact final exceeds pixel cap"); + let mut expected_settings = final_settings; + expected_settings.width = 1024; + expected_settings.height = 576; + assert_eq!(preview_settings, expected_settings, "camera, stage, background and other settings remain exact"); + let mut expected_options = before.raytrace.unwrap(); + expected_options.primary_samples = 1; + expected_options.progressive = Some(Default::default()); + expected_options.reflections.as_mut().unwrap().samples = 1; + assert_eq!(after.raytrace.unwrap(), expected_options, "no lighting, emission, shading effect or EV is discarded"); + assert_eq!(lowered["environment"], wire["environment"], "unopened HDR path and expected digest stay pinned"); + assert_eq!(lowered["raytrace"]["progressive"], json!({"samples_per_pixel":16,"seed":0})); + assert_eq!(wire, original); + } + + #[test] + fn interactive_small_and_extreme_aspects_fit_without_enlarging_or_zero_dimensions() { + for (width, height, expected) in [(320, 200, (320, 200)), (4096, 1, (1024, 1)), (1, 4096, (1, 1024))] { + let wire = json!({"integrator":"raytrace","settings":{"width":width,"height":height}}); + let output = interactive_params(&wire).unwrap(); + assert_eq!((output["settings"]["width"].as_u64().unwrap(), output["settings"]["height"].as_u64().unwrap()), (expected.0, expected.1)); + } + } + + #[test] + fn interactive_refuses_alternate_authorities_and_unknown_fields_without_io() { + let s = Session::default(); + let base = interactive_final_wire(); + for (key, value) in [ + ("setup", json!(null)), + ("setup", json!("Saved")), + ("replace", json!(false)), + ("replace", json!(true)), + ("integrator", json!("raster")), + ("progressive", json!(true)), + ("transparent_background", json!(true)), + ("denoise", json!(true)), + ("samples", json!(1)), + ("max_depth", json!(2)), + ("seed", json!(0)), + ("studio_weights", json!([1, 1, 1])), + ("unknown", json!(true)), + ("lens", json!(null)), + ] { + let mut wire = base.clone(); + wire[key] = value; + let error = match interactive(&s, &wire) { + Err(error) => error.to_string(), + Ok(_) => panic!("Interactive accepted conflicting input {key}"), + }; + assert!(!error.contains("could not read") && !error.contains("no image host"), "refuse before host/IO: {key}: {error}"); + } + for settings in [ + json!(null), + json!({"job":{"method":"cpu_raytrace"}}), + json!({"job":{"method":"gpu_path"}}), + json!({"exposure_ev":1.0}), + json!({"environment_rotation":1.0}), + json!({"width":0}), + json!({"mode":"final"}), + json!({"format":"exr"}), + ] { + let mut wire = base.clone(); + wire["settings"] = settings; + assert!(interactive_params(&wire).is_err()); + } + let mut missing = base.clone(); + missing.as_object_mut().unwrap().remove("settings"); + assert!(interactive_params(&missing).is_err()); + for wire in [json!(null), json!([]), json!(false)] { + assert!(interactive_params(&wire).is_err()); + } + assert!(s.render_job_host().is_none()); + } + + #[test] + fn interactive_refuses_invalid_or_unsupported_effects_before_unopened_hdr() { + let base = interactive_final_wire(); + // Retain numerically valid dielectric intent for capture-time certification. + // This fixture still mixes same-body mirror, emission and nonidentity effects; + // successful lowering is not scene or job admission. + let mut authored = base.clone(); + authored["raytrace"]["dielectrics"] = json!([{"body_index":0,"body_name":"receiver","ior":1.5,"absorption_per_mm":[0,0,0], + "boundary":"closed_box","thickness_mm":0}]); + let original = authored.clone(); + let authored_options: RaytraceOptions = serde_json::from_value(original["raytrace"].clone()).unwrap(); + let mut expected_options = authored_options.clone(); + expected_options.primary_samples = 1; + expected_options.progressive = Some(solidcraft_render::job::CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }); + expected_options.reflections.as_mut().unwrap().samples = 1; + let mut expected_settings: RenderSetup = serde_json::from_value(original["settings"].clone()).unwrap(); + expected_settings.width = 1024; + expected_settings.height = 576; + let mut expected_wire = original.clone(); + expected_wire["settings"] = serde_json::to_value(&expected_settings).unwrap(); + expected_wire["raytrace"] = serde_json::to_value(&expected_options).unwrap(); + + let lowered = interactive_params(&authored).unwrap(); + let lowered_options: RaytraceOptions = serde_json::from_value(lowered["raytrace"].clone()).unwrap(); + let lowered_settings: RenderSetup = serde_json::from_value(lowered["settings"].clone()).unwrap(); + assert_eq!(lowered_options.dielectrics, authored_options.dielectrics, "the exact original dielectric selector is retained"); + assert_eq!(lowered_options.surface_effects, authored_options.surface_effects, "shading intent is not removed"); + assert_eq!(lowered_options.emissions, authored_options.emissions, "surface emission is not removed"); + assert_eq!(lowered_options.reflections, expected_options.reflections, "only the selected reflection sample count changes"); + assert_eq!(lowered_options, expected_options, "only documented Interactive sampling is normalized"); + assert_eq!(lowered_settings, expected_settings, "camera, stage, background and other settings remain exact"); + assert_eq!(lowered["environment"], original["environment"], "unopened HDR path and expected digest remain exact"); + assert_eq!(lowered, expected_wire, "no other request field changes"); + assert_eq!(authored, original, "the authored final wire remains unchanged"); + + for (key, value) in [ + ("primary_samples", json!(0)), + ("exposure_ev", json!(33.0)), + ( + "anisotropic_faces", + json!([{"body_index":0,"body_name":"receiver","face":0,"tangent":[1,0,0], + "orientation":"zero","roughness_x":0.2,"roughness_y":0.4},null]), + ), + ("textures", json!([])), + ] { + let mut wire = base.clone(); + wire["raytrace"][key] = value; + assert!(interactive_params(&wire).is_err(), "unsupported {key} must not disappear"); + } + for (key, value) in [("thickness_mm", json!(1.0)), ("ior", json!(0.5))] { + let mut wire = authored.clone(); + wire["raytrace"]["dielectrics"][0][key] = value; + assert!(interactive_params(&wire).is_err(), "invalid dielectric {key} must refuse before unopened HDR"); + } + for (key, value) in [("intensity", json!(-1.0)), ("samples", json!(3))] { + let mut wire = base.clone(); + wire["environment"][key] = value; + assert!(interactive_params(&wire).is_err()); + } + let mut ambiguous = base.clone(); + ambiguous["raytrace"]["environment"] = json!({"color":[1.0,1.0,1.0],"intensity":1.0}); + assert!(interactive_params(&ambiguous).is_err()); + let mut orphaned_led_samples = base; + orphaned_led_samples["led_samples"] = json!(16); + assert!(interactive_params(&orphaned_led_samples).is_err()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn interactive_capture_reuses_cpu_scene_stage_and_admission_without_starting_a_job() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":8,"height":4,"body_name":"receiver"})).unwrap(); + s.execute( + "appearance.assign", + &json!({"bodies":["receiver"],"color":"#4080c0", + "pbr":{"metallic":1.0,"roughness":0.25,"dielectric_ior":1.5}}), + ) + .unwrap(); + s.execute("render.scene", &json!({})).unwrap(); + let subject = crate::product_scene::extract(&s).unwrap(); + let host = solidcraft_render::job::CpuHost::for_platform().unwrap(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let mut wire = interactive_final_wire(); + wire.as_object_mut().unwrap().remove("environment"); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let captured = interactive(&s, &wire).unwrap(); + assert_eq!((captured.request.width, captured.request.height), (1024, 576)); + assert_eq!(captured.request.integrator, Integrator::Raytrace); + assert_eq!(captured.request.raytrace.as_ref().unwrap().exposure_ev, 1.25); + let body = captured.scene.meshes.iter().find(|mesh| mesh.name == "receiver").unwrap(); + assert_eq!(body.surface, subject.meshes[0].surface); + assert_eq!(body.faces, subject.meshes[0].faces); + assert!(std::sync::Arc::ptr_eq(&body.mesh, &subject.meshes[0].mesh)); + assert_eq!(captured.scene.meshes.len(), 2, "subject and render-only floor are both captured"); + assert!(captured.scene.meshes.iter().any(|mesh| mesh.name == "__render_stage__/floor")); + assert_eq!(captured.options, solidcraft_render::job::JobOptions::default()); + assert!(captured.environment.is_none()); + assert_eq!(host.admitted_bytes(), 0, "capture validates but does not submit/reserve a job"); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + assert_eq!(wire["settings"]["width"], 3840); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn nested_command_fixture() -> (Session, Value) { + let mut s = Session::default(); + for (name, length, width, height) in [("Outer", 20, 20, 4), ("Inner", 10, 10, 2)] { + s.execute( + "solid.box", + &json!({ + "length":length,"width":width,"height":height,"center":[0,0,2], + "operation":"new","body_name":name, + }), + ) + .unwrap(); + } + s.execute("render.scene", &json!({})).unwrap(); + let scene = crate::product_scene::extract(&s).unwrap(); + assert_eq!(scene.meshes.len(), 2); + let dielectrics: Vec<_> = scene + .meshes + .iter() + .enumerate() + .map(|(index, body)| { + assert!(matches!(body.name.as_str(), "Outer" | "Inner")); + json!({ + "body_index":index,"body_name":body.name,"boundary":"closed_box","ior":1.0, + "absorption_per_mm":if body.name == "Outer" { [0.1,0.2,0.0] } else { [0.3,0.4,0.0] }, + "thickness_mm":0.0, + }) + }) + .collect(); + let mut camera = solidcraft_render::Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + camera.set_view(solidcraft_render::StandardView::Top); + camera.target = solidcraft_geom::Vec3::new(0.0, 0.0, 2.0); + let host = solidcraft_render::job::CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), solidcraft_render::job::HostKind::NativeWorker); + assert!(host.is_available(), "this native test requires an available real CPU worker"); + s.set_render_job_host(Some(host)).unwrap(); + let wire = json!({ + "integrator":"raytrace","nested_media":true, + "settings":{"width":1,"height":1,"camera":camera,"background":[255,255,255],"job":null}, + "raytrace":{"dielectrics":dielectrics,"lights":[],"shadows":false, + "environment":{"color":[1,1,1],"intensity":1}}, + }); + (s, wire) + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn command_nested_opt_in_reaches_retained_job_options_and_real_beer_transport() { + use solidcraft_render::job::{JobId, Phase}; + let (mut s, wire) = nested_command_fixture(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let document = s.doc.clone(); + for value in [None, Some(false)] { + let mut default = wire.clone(); + if let Some(value) = value { + default["nested_media"] = json!(value); + } else { + default.as_object_mut().unwrap().remove("nested_media"); + } + for command in ["render.preflight", "render.start"] { + let error = s.execute(command, &default).unwrap_err().to_string(); + assert!(error.contains("nested, touching or overlapping dielectric volumes are unsupported"), "{command}: {error}"); + } + } + let checked = s.execute("render.preflight", &wire).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]); + let started = s.execute("render.start", &wire).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.options, solidcraft_render::job::JobOptions { nested_media: true, ..Default::default() }); + let retained = s.execute("render.status", &json!({"job":id})).unwrap(); + assert_eq!(retained["options"]["nested_media"], true); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + // Independent Beer oracle: outer2mm + inner2mm, replacing the parent + // interval, yields exp(-.8), exp(-1.2),1 -> Reinhard+sRGB [151,132,188]. + assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn command_nesting_keeps_default_false_rejects_gpu_controls_and_captures_progressive_glass() { + use solidcraft_render::job::{JobId, JobOptions, Phase}; + let (mut s, wire) = nested_command_fixture(); + for (key, value) in [("samples", json!(2)), ("max_depth", json!(2)), ("seed", json!(7)), ("denoise", json!(true)), ("lens", json!({}))] { + let mut invalid = wire.clone(); + invalid[key] = value; + for command in ["render.preflight", "render.start"] { + assert!(s.execute(command, &invalid).is_err(), "{command} accepted unrelated control {key}"); + } + } + let mut progressive = wire.clone(); + progressive["raytrace"]["progressive"] = json!({"samples_per_pixel":2,"seed":0}); + // Original narrow perspective fixture: every possible pixel jitter ray + // enters both boxes, rather than allowing primary misses/background. + progressive["settings"]["camera"]["fov"] = json!(1.0e-6); + // This previously blanket-negative branch is now an actual supported + // progressive transport/capture case. GPU-only control refusals above + // and the default nesting assertions below are unchanged. + let checked = s.execute("render.preflight", &progressive).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]); + assert_eq!(checked["request"]["raytrace"]["progressive"], progressive["raytrace"]["progressive"]); + let started = s.execute("render.start", &progressive).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert!(status.options.nested_media); + let captured = status.request.raytrace.as_ref().unwrap(); + assert_eq!(captured.progressive.unwrap().samples_per_pixel, 2); + assert_eq!(captured.progressive.unwrap().seed, 0); + assert_eq!(serde_json::to_value(&captured.dielectrics).unwrap(), wire["raytrace"]["dielectrics"]); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (1, 1)); + // Camera is exterior at z52. At every box face its full jitter cone + // lies within52*tan(1e-6) < 0.000053mm of the axis, far inside the + // inner +/-5mm face. Even using twice the actual half-angle bounds, + // cos(theta)>1-2e-12. Parent-only and child lengths are each2/cos mm. + // IOR1 removes Fresnel/refraction; scalar Beer is exp(-.8/cos), + // exp(-1.2/cos),1. Their bounded variation is far below the nearest + // integer thresholds of existing Reinhard/sRGB: [151,132,188]. + // Actual primary-background pixels would be255 and fail this oracle. + // This remains a command-route smoke, not a Fresnel/TIR quality case. + assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]); + let interactive = interactive_params(&wire).unwrap(); + assert_eq!(interactive["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]); + assert_eq!(interactive["nested_media"], true); + assert!(interactive["raytrace"]["progressive"].is_object()); + + // Ordinary CPU requests retain the exact default JobOptions; omission is + // not silently promoted to nesting by adding this explicit opt-in. + let mut opaque = wire; + opaque.as_object_mut().unwrap().remove("nested_media"); + opaque["raytrace"].as_object_mut().unwrap().remove("dielectrics"); + s.execute("render.preflight", &opaque).unwrap(); + let started = s.execute("render.start", &opaque).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let status = s.render_job_handle(id).unwrap().wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.options, JobOptions::default()); + let retained = s.execute("render.status", &json!({"job":id})).unwrap(); + assert_eq!(retained["options"]["nested_media"], false); + } +} + +/// Resolve portable intent before choosing an executor. Legacy requests are left intact; +/// complete saved jobs cannot be silently overridden by a second set of runtime controls. +enum SavedHdr { + Cpu(CpuHdrEnvironment), + Gpu(GpuHdrEnvironment), +} + +struct Normalized { + params: Value, + hdr: Option, + surfaces: solidcraft_doc::render_surface::SurfaceBindings, + optics: solidcraft_doc::render_optics::OpticalBindings, +} + +fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result> { + // Validate the new payload by reference even if this turns out to be an + // unsaved request. Never clone an unbounded caller-owned light array. + let raster_override = params + .get("raster_lights") + .map(|value| solidcraft_render::job::deserialize_raster_lights(value).map_err(|e| bad(command, e.to_string()))) + .transpose()?; + // Validate both local arrays by reference before any saved setup or JSON clone. + if let Some(value) = params.get("raster_punctual_lights") { + let _ = solidcraft_render::job::deserialize_raster_punctual_lights(value).map_err(|e| bad(command, e.to_string()))?; + } + if let Some(value) = params.get("raster_area_lights") { + let _ = solidcraft_render::job::deserialize_raster_area_lights(value).map_err(|e| bad(command, e.to_string()))?; + } + let local_intent = ["raster_punctual_lights", "raster_area_lights"].into_iter().any(|key| params.get(key).is_some_and(|v| !v.is_null())); + if local_intent { + let inline_saved = params.get("settings").and_then(|v| v.get("job")).is_some_and(|v| !v.is_null()); + let named_saved = params.get("setup").and_then(Value::as_str).and_then(|name| s.doc.render.setups.get(name)).is_some_and(|v| v.job.is_some()); + if inline_saved || named_saved { + return Err(bad(command, "runtime Raster local lights require settings.job: null; saved local-light authoring is not supported yet")); + } + } + let Some(object) = params.as_object() else { + return Ok(None); + }; + let named = object.get("setup").filter(|value| !value.is_null()); + let inline = object.get("settings").filter(|value| !value.is_null()); + if named.is_some() && inline.is_some() { + return Err(bad(command, "choose either setup or settings")); + } + let mut settings = if let Some(value) = inline { + if value.get("job").is_none_or(Value::is_null) { + return Ok(None); + } + RenderSetup::deserialize(value).map_err(|e| bad(command, e.to_string()))? + } else if let Some(settings) = named.and_then(Value::as_str).and_then(|name| s.doc.render.setups.get(name)) { + if settings.job.is_none() { + return Ok(None); + } + settings.validate().map_err(|e| bad(command, e.to_string()))?; + settings.clone() + } else { + return Ok(None); + }; + if let Some(key) = object.keys().find(|key| { + !matches!( + key.as_str(), + "setup" + | "settings" + | "replace" + | "studio_weights" + | "progressive_feedback" + | "cpu_progressive_every_pass" + | "raster_lights" + | "raster_punctual_lights" + | "raster_area_lights" + ) + }) { + return Err(bad( + command, + format!( + "saved job already defines the active method and its options; runtime `{key}` cannot override it (use job: null for a runtime request)" + ), + )); + } + settings.validate().map_err(|e| bad(command, e.to_string()))?; + s.doc.render.validate_resources(&settings).map_err(|e| bad(command, e.to_string()))?; + let Some(job) = settings.job.take() else { + return Ok(None); + }; + let optics = std::mem::take(&mut settings.optics); + let surfaces = std::mem::take(&mut settings.surfaces); + let mut hdr = None; + let mut lowered = match job { + RenderJob::Raster { transparent_background, lights } => { + if lights.is_some() && object.contains_key("raster_lights") { + return Err(bad(command, "saved Raster lights are authoritative; remove the runtime raster_lights override")); + } + let mut request = json!({"transparent_background":transparent_background}); + if lights.is_some() { + request["raster_lights"] = serde_json::to_value(lights).map_err(|e| bad(command, e.to_string()))?; + } + request + } + RenderJob::CpuRaytrace { options } => { + hdr = options.hdr.map(SavedHdr::Cpu); + let raytrace = options.to_runtime(settings.exposure_ev).map_err(|e| bad(command, e.to_string()))?; + // The legacy CPU path reads EV from RaytraceOptions. There is one saved authority. + settings.exposure_ev = 0.0; + json!({"integrator":"raytrace","raytrace":raytrace}) + } + RenderJob::GpuPath { transparent_background, options } => { + hdr = options.hdr.map(SavedHdr::Gpu); + json!({ + "progressive":true, + "transparent_background":transparent_background, + "samples":options.samples,"max_depth":options.max_depth,"seed":options.seed, + "lens":options.lens,"lighting":options.lighting,"tone_map":options.tone_map, + "denoise":options.denoise,"environment":options.environment, + "finishing":options.finishing,"backdrop":options.backdrop,"linear_exr":options.linear_exr, + "adaptive":options.adaptive,"transmission_samples":options.transmission_samples,"volume":options.volume,"nested_media":options.nested_media,"aging":options.aging + }) + } + }; + lowered["settings"] = serde_json::to_value(settings).map_err(|e| bad(command, e.to_string()))?; + if let Some(lights) = raster_override { + // Only the already validated, bounded representation is materialized. + lowered["raster_lights"] = serde_json::to_value(lights).map_err(|e| bad(command, e.to_string()))?; + } + if let Some(weights) = object.get("studio_weights") { + lowered["studio_weights"] = weights.clone(); + } + if let Some(replace) = object.get("replace") { + lowered["replace"] = replace.clone(); + } + if let Some(feedback) = object.get("progressive_feedback") { + lowered["progressive_feedback"] = feedback.clone(); + } + if let Some(every_pass) = object.get("cpu_progressive_every_pass") { + lowered["cpu_progressive_every_pass"] = every_pass.clone(); + } + Ok(Some(Normalized { params: lowered, hdr, surfaces, optics })) +} + +fn prepare(s: &Session, params: &Value, command: &str) -> Result { + let normalized = normalize_saved_job(s, params, command)?; + let saved_hdr = normalized.as_ref().and_then(|normalized| normalized.hdr.as_ref()); + let params = normalized.as_ref().map_or(params, |normalized| &normalized.params); + if params.get("progressive").and_then(Value::as_bool) == Some(true) { + if params.get("cpu_progressive_every_pass").is_some() { + return Err(bad(command, "cpu_progressive_every_pass requires CPU progressive raytracing")); + } + let hdr = match saved_hdr { + Some(SavedHdr::Gpu(hdr)) => Some(*hdr), + Some(SavedHdr::Cpu(_)) => return Err(bad(command, "saved CPU HDR cannot enter a GPU request")), + None => None, + }; + return prepare_progressive( + s, + params, + command, + normalized.is_some(), + hdr, + normalized.as_ref().map(|n| &n.surfaces), + normalized.as_ref().map(|n| &n.optics), + ); + } + let gpu_raytrace = + params.get("raytrace").and_then(Value::as_object).is_some_and(|o| ["clear_coats", "textures"].iter().any(|key| o.contains_key(*key))); + if gpu_raytrace + || params.get("environment").is_some_and(|e| e.get("kind").is_some()) + || ["lens", "lighting", "tone_map"].iter().any(|key| params.get(*key).is_some()) + || params.get("denoise").is_some_and(|value| value != &json!(false)) + { + return Err(bad( + command, + "runtime GPU transmission, texture, lens, environment, lighting, tone-map and denoise controls require progressive rendering", + )); + } + let mut input = Start::deserialize(params).map_err(|e| bad(command, e.to_string()))?; + if input.cpu_progressive_every_pass.is_some() + && (input.integrator != Integrator::Raytrace || input.progressive || input.raytrace.as_ref().and_then(|options| options.progressive).is_none()) + { + return Err(bad(command, "cpu_progressive_every_pass requires CPU progressive raytracing")); + } + solidcraft_render::job::validate_raster_lights(&input.raster_lights).map_err(job_error)?; + solidcraft_render::job::validate_raster_punctual_lights(&input.raster_punctual_lights).map_err(job_error)?; + solidcraft_render::job::validate_raster_area_lights(&input.raster_area_lights).map_err(job_error)?; + if (input.raster_lights.is_some() || input.raster_punctual_lights.is_some() || input.raster_area_lights.is_some()) + && (input.integrator != Integrator::Raster + || input.progressive + || input.progressive_feedback + || input.nested_media + || input.raytrace.is_some() + || input.studio_weights.is_some() + || input.environment.is_some()) + { + return Err(bad(command, "explicit Raster lights require Raster without CPU/GPU controls, environment or studio_weights")); + } + if input.progressive_feedback + && (input.integrator != Integrator::Raytrace || input.raytrace.as_ref().and_then(|options| options.progressive).is_none()) + { + return Err(bad(command, "progressive_feedback requires CPU progressive raytracing")); + } + validate_studio_weights(input.studio_weights, command)?; + if input.integrator == Integrator::Raytrace && input.studio_weights.is_some() { + return Err(bad(command, "studio_weights apply to raster or the implicit GPU studio; use explicit CPU light intensities")); + } + if input.progressive { + return prepare_progressive(s, params, command, false, None, None, None); + } + if input.denoise { + return Err(bad(command, "denoise requires GPU progressive rendering")); + } + if input.samples.is_some() || input.max_depth.is_some() || input.seed.is_some() { + return Err(bad(command, "sampling controls require progressive rendering")); + } + if input.setup.is_some() && input.settings.is_some() { + return Err(bad(command, "choose either setup or settings")); + } + // Reject unavailable execution before capturing authoritative product meshes. + // Runtime services are independent of the document and can be checked cold. + let host = s.render_job_host().ok_or_else(|| bad(command, "no image host is installed"))?; + if !host.is_available() { + return Err(bad(command, "image host is unavailable")); + } + host.validate_integrator(input.integrator).map_err(job_error)?; + lower_led(&mut input, command)?; + if input.integrator == Integrator::Raster && input.raytrace.is_some() { + return Err(bad(command, "raytrace options require integrator: raytrace")); + } + if input.integrator == Integrator::Raytrace && input.transparent_background { + return Err(bad(command, "raytrace supports opaque backgrounds only")); + } + if let Some(options) = &input.raytrace { + options.retained_bytes().map_err(job_error)?; + if options.directional_shadow_transmission { + if input.nested_media { + return Err(bad(command, "directional shadow transmission does not support nested media")); + } + if saved_hdr.is_some() || input.environment.is_some() { + return Err(bad(command, "directional shadow transmission does not support HDR environments")); + } + } + options.budget.validate_execution().map_err(job_error)?; + // Check the complete image envelope before any source file is read. + let dimensions = if let Some(name) = &input.setup { + let settings = s.doc.render.setups.get(name).ok_or_else(|| bad(command, "no saved render setup with that name"))?; + (settings.width, settings.height) + } else if let Some(settings) = &input.settings { + (settings.width, settings.height) + } else { + let defaults = RenderSetup::default(); + (defaults.width, defaults.height) + }; + options.budget.validate_image(dimensions.0, dimensions.1, options.progressive).map_err(job_error)?; + } + let environment = if let Some(saved_hdr) = saved_hdr { + let SavedHdr::Cpu(hdr) = saved_hdr else { + return Err(bad(command, "saved GPU HDR cannot enter a CPU request")); + }; + if input.integrator != Integrator::Raytrace || input.environment.is_some() { + return Err(bad(command, "saved CPU HDR requires raytrace without a runtime environment override")); + } + let resource = s.doc.render.resources.required(&hdr.resource).map_err(|e| bad(command, e.to_string()))?; + Some( + solidcraft_render::lighting::environment_input::EnvironmentInput::new(resource.source(), hdr.rotation_rad, hdr.intensity, hdr.samples) + .map_err(|e| bad(command, e.to_string()))?, + ) + } else if let Some(environment) = &input.environment { + if input.integrator != Integrator::Raytrace { + return Err(bad(command, "environment requires raytrace")); + } + let source = if let Some(id) = environment.resource { + if !environment.path.is_empty() || environment.expected_sha256.is_some() { + return Err(bad(command, "choose an embedded HDR resource or a file path with optional expected_sha256")); + } + s.doc.render.resources.required(&id).map_err(|e| bad(command, e.to_string()))?.source() + } else { + if environment.path.is_empty() + || environment.path.len() > 4096 + || environment.path.capacity() > 4096 + || environment.path.chars().any(char::is_control) + { + return Err(bad(command, "environment requires a bounded HDR input path")); + } + let bytes = + solidcraft_io::vfs::read(&environment.path, solidcraft_render::lighting::MAX_HDR_BYTES).map_err(|e| bad(command, e.to_string()))?; + if environment.expected_sha256.is_some_and(|id| id != solidcraft_doc::render_resources::HdrId::of(&bytes)) { + return Err(bad(command, "HDR file changed since selection; inspect and select it again")); + } + solidcraft_render::lighting::HdrSource::new(bytes).map_err(|e| bad(command, e.to_string()))? + }; + Some( + solidcraft_render::lighting::environment_input::EnvironmentInput::new( + source, + environment.rotation_radians, + environment.intensity, + environment.samples, + ) + .map_err(|e| bad(command, e.to_string()))?, + ) + } else { + None + }; + let mut scene = crate::product_scene::extract(s)?; + if environment.is_some() { + input.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()).validate_environment_reflections(&scene).map_err(job_error)?; + } + let settings = if let Some(name) = &input.setup { + s.doc.render.setups.get(name).cloned().ok_or_else(|| bad(command, "no saved render setup with that name"))? + } else if let Some(settings) = &input.settings { + settings.clone() + } else { + let mut settings = RenderSetup::default(); + if let Some(camera) = s.camera { + settings.camera = camera; + } else { + settings.camera.fit(&scene.bounds); + } + settings + }; + if input.integrator == Integrator::Raster && !settings.stage.is_empty() { + return Err(bad(command, "passive stages require a raytrace executor")); + } + super::staging::apply(&mut scene, &settings, command)?; + let budget = input.raytrace.as_ref().map_or(solidcraft_render::job::CpuBudget::Compact, |o| o.budget); + if input.integrator == Integrator::Raytrace { + settings.validate_for_cpu(budget).map_err(|e| bad(command, e.to_string()))?; + budget.validate_execution().map_err(job_error)?; + budget.validate_image(settings.width, settings.height, input.raytrace.as_ref().and_then(|o| o.progressive)).map_err(job_error)?; + } else { + settings.validate().map_err(|e| bad(command, e.to_string()))?; + } + // Raster captures the existing exposure authority. Legacy environment controls + // still have no transport here and are reported/refused under their old policy. + if (input.raster_lights.is_some() || input.raster_punctual_lights.is_some() || input.raster_area_lights.is_some()) + && (settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0) + { + return Err(bad(command, "explicit Raster lights do not implement environment controls")); + } + let ignored = if input.integrator == Integrator::Raster { ignored_controls(&settings) } else { Vec::new() }; + if input.integrator != Integrator::Raster + && (settings.exposure_ev != 0.0 || settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0) + { + return Err(bad(command, "exposure and environment controls are not supported by the R4a CPU image executor")); + } + let mut descriptor = host.descriptor_for(input.integrator).map_err(job_error)?; + if input.integrator == Integrator::Raytrace { + descriptor.limits = budget.image_limits(input.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())); + } + let expected_executor = descriptor.id.clone(); + let mut backend = s.render_backend(); + backend.executors = vec![descriptor]; + let mut features = scene.required_features(); + if environment.is_some() { + features.push(solidcraft_render::RenderFeature::Hdri); + } + let refraction = input.raytrace.as_ref().is_some_and(|options| !options.dielectrics.is_empty()); + if refraction && !features.contains(&solidcraft_render::RenderFeature::Refraction) { + features.push(solidcraft_render::RenderFeature::Refraction); + } + let environment_info = environment.as_ref().map(|e| e.metadata()); + let resolved = solidcraft_render::resolve_request( + &[backend], + &RenderRequest { + backend: Some(settings.backend.clone()), + mode: settings.mode, + operation: RenderOperation::Image, + width: u64::from(settings.width), + height: u64::from(settings.height), + format: Some(settings.format), + features, + policy: Default::default(), + }, + ) + .map_err(|e| bad(command, e.to_string()))?; + if resolved.executor != expected_executor { + return Err(bad(command, "resolved executor is not installed as an image job host")); + } + let request = ImageRequest { + cpu_progressive_every_pass: input.cpu_progressive_every_pass.unwrap_or(true), + raster_punctual_lights: input.raster_punctual_lights.take(), + raster_area_lights: input.raster_area_lights.take(), + raster_exposure_ev: if input.integrator == Integrator::Raster { settings.exposure_ev } else { 0.0 }, + raster_lights: input.raster_lights.take(), + studio_weights: validate_studio_weights(input.studio_weights, command)?, + environment: None, + textures: None, + integrator: input.integrator, + raytrace: input.raytrace.take(), + camera: settings.camera, + width: settings.width, + height: settings.height, + background: settings.background, + transparent_background: input.transparent_background, + }; + let options = solidcraft_render::job::JobOptions { nested_media: input.nested_media, ..Default::default() }; + let mut admission = if input.progressive_feedback { + host.admit_cpu_protected_partial_with_environment_and_options(&scene, &request, options, environment.as_ref()).map_err(job_error)? + } else { + host.admit(&scene, &request, options).map_err(job_error)? + }; + let retained_lights = request.raytrace.as_ref().map_or(Ok(0), |o| o.retained_bytes()).map_err(job_error)?; + let retained_lights = retained_lights + .checked_add(request.raster_lights_retained_bytes().map_err(job_error)?) + .ok_or_else(|| bad(command, "retained light metadata overflow"))?; + let retained_environment = + if environment_info.is_some() { std::mem::size_of::() as u64 } else { 0 }; + let retained_request_bytes = retained_lights.checked_add(retained_environment).ok_or_else(|| bad(command, "request metadata overflow"))?; + + if !input.progressive_feedback { + let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(environment_bytes) + .and_then(|v| v.checked_add(retained_request_bytes)) + .filter(|v| *v <= budget.limits().max_job_bytes) + .ok_or_else(|| bad(command, "environment job exceeds per-job memory limit"))?; + admission.preparation_bytes = + admission.preparation_bytes.checked_add(environment_bytes).ok_or_else(|| bad(command, "environment admission overflow"))?; + } + let transparency = match input.integrator { + Integrator::Raster => "sorted_alpha_approximation", + Integrator::Raytrace if refraction => "physical_transmission", + Integrator::Raytrace => "opaque_only", + }; + let reply = json!({"ignored_controls":ignored,"stage_panels":settings.stage.len(),"stage_transport":"CPU direct/specular only; no diffuse interreflection", "cpu_budget":budget,"cpu_limits":budget.limits(),"environment":environment_info,"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":refraction,"dielectric_boundaries":if refraction {vec!["thin_sheet","closed_box"]} else {Vec::<&str>::new()}}); + Ok(Prepared { + progressive_feedback: input.progressive_feedback, + replace: input.replace, + scene, + request, + reply, + environment, + executor: resolved.executor, + options, + }) +} + +fn prepare_progressive( + s: &Session, + params: &Value, + command: &str, + require_gpu_path: bool, + saved_hdr: Option, + saved_surfaces: Option<&solidcraft_doc::render_surface::SurfaceBindings>, + saved_optics: Option<&solidcraft_doc::render_optics::OpticalBindings>, +) -> Result { + let cpu_raytrace = params + .get("raytrace") + .and_then(Value::as_object) + .is_some_and(|o| o.keys().any(|key| !matches!(key.as_str(), "dielectrics" | "clear_coats" | "textures"))); + if params.get("integrator").is_some_and(|v| v.as_str() != Some("raster")) + || cpu_raytrace + || params.get("led_strip").is_some() + || params.get("led_samples").is_some() + || params.get("environment").is_some_and(|e| e.is_object() && e.get("kind").is_none()) + { + return Err(bad(command, "progressive rendering does not accept CPU raytrace, environment or LED options")); + } + let mut input: ProgressiveStart = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + if input.progressive_feedback { + return Err(bad(command, "progressive_feedback requires CPU progressive raytracing, not GPU progressive rendering")); + } + validate_studio_weights(input.studio_weights, command)?; + if input.studio_weights.is_some() && (input.lighting.is_some() || input.environment.is_some() || saved_hdr.is_some()) { + return Err(bad(command, "studio_weights require the implicit GPU studio without environment lighting")); + } + if input.integrator != Integrator::Raster || !input.progressive { + return Err(bad(command, "progressive rendering requires the registered GPU request method")); + } + if input.setup.is_some() && input.settings.is_some() { + return Err(bad(command, "choose either setup or settings")); + } + let mut scene = crate::product_scene::extract(s)?; + if !input.progressive + && (!input.raytrace.dielectrics.is_empty() + || !input.raytrace.clear_coats.is_empty() + || !input.raytrace.textures.is_empty() + || input.lens.is_some() + || input.lighting.is_some() + || input.tone_map.is_some() + || input.environment.is_some() + || input.denoise) + { + return Err(bad( + command, + "runtime transmission, clear-coat, texture, lens, environment, lighting, tone-map and denoise controls require progressive rendering", + )); + } + if let Some(bindings) = saved_surfaces.filter(|bindings| !bindings.is_empty()) { + if !input.raytrace.textures.is_empty() { + return Err(bad(command, "saved surfaces cannot be combined with runtime texture overrides")); + } + input.raytrace.textures = super::surface_bindings::resolve(s, &scene, bindings, command)?; + } + if let Some(bindings) = saved_optics.filter(|b| !b.is_empty()) { + if !input.raytrace.dielectrics.is_empty() || !input.raytrace.clear_coats.is_empty() { + return Err(bad(command, "saved optical bindings cannot be mixed with transient optical overrides")); + } + input.raytrace.dielectrics = super::optical_bindings::resolve(s, &scene, bindings, command)?; + } + super::transmission::apply(&mut scene, &input.raytrace.dielectrics, command)?; + super::clear_coat::apply(&mut scene, &input.raytrace.clear_coats, command)?; + let settings = if let Some(name) = &input.setup { + s.doc.render.setups.get(name).cloned().ok_or_else(|| bad(command, "no saved render setup with that name"))? + } else if let Some(settings) = &input.settings { + settings.clone() + } else { + let mut settings = RenderSetup::default(); + if let Some(camera) = s.camera { + settings.camera = camera; + } else { + settings.camera.fit(&scene.bounds); + } + settings + }; + settings.validate_for_gpu().map_err(|e| bad(command, e.to_string()))?; + if settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0 { + return Err(bad(command, "environment controls are not supported by the installed image executors")); + } + if !input.progressive && (input.samples.is_some() || input.max_depth.is_some() || input.seed.is_some() || settings.exposure_ev != 0.0) { + return Err(bad(command, "sampling and exposure controls require progressive rendering")); + } + super::staging::apply(&mut scene, &settings, command)?; + let mut options = solidcraft_render::job::JobOptions::default(); + if let Some(samples) = input.samples { + options.samples = samples; + } + if let Some(depth) = input.max_depth { + options.max_depth = depth; + } + if let Some(seed) = input.seed { + options.seed = seed; + } + options.exposure_ev = settings.exposure_ev; + options.lens = input.lens; + options.lighting = input.lighting; + options.tone_map = input.tone_map.unwrap_or_default(); + options.denoise = input.denoise; + options.finishing = input.finishing; + options.backdrop = input.backdrop; + options.linear_exr = input.linear_exr; + options.aging = super::effects::resolve_aging(s, &scene, &input.aging, command)?; + options.nested_media = input.nested_media; + options.volume = input.volume; + options.adaptive = input.adaptive; + options.transmission_samples = input.transmission_samples.unwrap_or(1); + options.validate().map_err(job_error)?; + if let Some(super::environment::Input::BuiltinHdr { id, .. }) = &input.environment + && options.lighting.as_ref().is_some_and(|lighting| lighting.sun.is_some()) + && super::library::owns_sun(id, command)? + { + return Err(bad(command, "built-in HDR and analytic lighting cannot both own the sun")); + } + let environment = if let Some(hdr) = saved_hdr { + if input.environment.is_some() { + return Err(bad(command, "saved GPU HDR cannot have a runtime environment override")); + } + let resource = s.doc.render.resources.required(&hdr.resource).map_err(|e| bad(command, e.to_string()))?; + Some(std::sync::Arc::new( + solidcraft_render::lighting::environment::EnvironmentSource::from_hdr( + resource.source(), + hdr.rotation_rad, + hdr.intensity, + hdr.assume_linear_srgb, + ) + .map_err(|e| bad(command, e.to_string()))?, + )) + } else { + input.environment.as_ref().map(|source| source.capture(&s.doc.render.resources, command)).transpose()? + }; + let mut features = scene.required_features(); + if environment.is_some() { + features.push(solidcraft_render::RenderFeature::Hdri); + } + if input.progressive { + features.push(solidcraft_render::RenderFeature::Progressive); + if scene.has_transmission() { + features.push(solidcraft_render::RenderFeature::Refraction); + } + } + let mut backend = s.render_backend(); + if require_gpu_path { + backend.executors.retain(|executor| executor.id.as_str() == "gpu-path"); + if backend.executors.is_empty() { + return Err(bad(command, "saved gpu_path method requires an installed gpu-path executor")); + } + } + let resolved = solidcraft_render::resolve_request( + &[backend], + &RenderRequest { + backend: Some(settings.backend.clone()), + mode: settings.mode, + operation: RenderOperation::Image, + width: u64::from(settings.width), + height: u64::from(settings.height), + format: Some(settings.format), + features, + policy: Default::default(), + }, + ) + .map_err(|e| bad(command, e.to_string()))?; + if require_gpu_path && resolved.executor.as_str() != "gpu-path" { + return Err(bad(command, "saved gpu_path method requires the gpu-path executor; another progressive executor cannot substitute for it")); + } + if options.denoise && resolved.executor.as_str() != "gpu-path" { + return Err(bad(command, "denoise requires the native gpu-path executor")); + } + let host = s.render_jobs.host_for(&resolved.executor).ok_or_else(|| bad(command, "resolved executor is not installed as an image job host"))?; + if !host.is_available() { + return Err(bad(command, "image host is unavailable")); + } + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: validate_studio_weights(input.studio_weights, command)?, + integrator: Default::default(), + raytrace: None, + environment, + camera: settings.camera, + width: settings.width, + height: settings.height, + background: settings.background, + transparent_background: input.transparent_background, + textures: super::textures::capture(&scene, &input.raytrace.textures, command)?, + }; + let mut admission = host.admit(&scene, &request, options).map_err(job_error)?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(request.retained_resource_metadata_bytes()) + .filter(|bytes| *bytes <= host.job_limit_bytes()) + .ok_or_else(|| bad(command, "GPU work and retained metadata exceed the per-job limit"))?; + let refraction = input.progressive && scene.has_transmission(); + let reply = json!({"stage_panels":settings.stage.len(),"resolved":resolved,"admission":admission,"request":request,"textures":request.textures.as_ref().map(|resources|resources.summary()),"scene_generation":s.revision,"host":host.kind(),"transparency":if refraction {"physical_transmission"} else if input.progressive {"opaque_only"} else {"sorted_alpha_approximation"},"options":options,"environment":request.environment.as_ref().map(|source|source.info()),"refraction":refraction,"dielectric_boundaries": if resolved.executor.as_str() == "gpu-path" {vec!["thin_sheet","closed_box","closed_mesh"]} else {Vec::<&str>::new()}}); + let mut reply = reply; + if options.denoise { + reply["denoising"] = json!({ + "method":"edge_aware_atrous", "passes":3, "steps":[1,2,4], + "guides":"deterministic_center_ray_albedo_normal_position_depth", + "bypass":"glass, smooth metal/coat, emitter, background and partial coverage first hits", + "limitation":"first-hit guides do not reconstruct reflection/refraction or depth-of-field correspondences", + "raw_linear_accumulator_preserved":true, "output_stage":"linear_before_tone_map" + }); + } + Ok(Prepared { + progressive_feedback: false, + replace: input.replace, + scene, + request, + reply, + executor: resolved.executor, + options, + environment: None, + }) +} + +/// Nonneutral environment controls the Raster image executor still cannot apply. +fn ignored_controls(settings: &RenderSetup) -> Vec<&'static str> { + let mut ignored = Vec::new(); + if settings.environment_rotation != 0.0 { + ignored.push("environment_rotation"); + } + if settings.environment_intensity != 1.0 { + ignored.push("environment_intensity"); + } + ignored +} + +pub(super) fn preflight(s: &mut Session, params: &Value) -> Result { + prepare(s, params, "render.preflight").map(|p| p.reply) +} + +pub(super) fn start(s: &mut Session, params: &Value) -> Result { + let p = prepare(s, params, "render.start")?; + let execution = crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment }; + let status = if p.progressive_feedback { + s.render_jobs.start_with_environment_and_feedback(s.revision, p.scene, p.request, p.replace, execution, true) + } else { + s.render_jobs.start_with_environment(s.revision, p.scene, p.request, p.replace, execution) + } + .map_err(job_error)?; + let mut status = json!(status); + if let (Some(out), Some(ignored)) = (status.as_object_mut(), p.reply.get("ignored_controls")) { + out.insert("ignored_controls".into(), ignored.clone()); + } + Ok(status) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Regrade { + job: JobId, + presentation: solidcraft_render::job::presentation::Presentation, +} +pub(super) fn regrade(s: &mut Session, params: &Value) -> Result { + let input: Regrade = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.regrade", e.to_string()))?; + input.presentation.validate().map_err(job_error)?; + Ok(json!(s.render_jobs.regrade(input.job, input.presentation).map_err(job_error)?)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Job { + job: JobId, +} + +pub(super) fn status(s: &mut Session, params: &Value) -> Result { + let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; + Ok(json!(s.render_jobs.status(input.job).map_err(job_error)?)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Pin { + job: Option, +} +pub(super) fn pin(s: &mut Session, params: &Value) -> Result { + if params.get("job").is_none() { + return Err(bad("render.result.pin", "job or explicit null is required")); + } + let input: Pin = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.pin", e.to_string()))?; + Ok(json!({"frame":s.render_jobs.pin(input.job).map_err(job_error)?})) +} + +pub(super) fn copy(s: &mut Session, params: &Value) -> Result { + let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let frame = s + .render_jobs + .handle(input.job) + .map_err(job_error)? + .frame() + .map_err(job_error)? + .ok_or_else(|| bad("render.result.copy", "render has no completed image"))?; + let size = (u64::from(frame.info.width), u64::from(frame.info.height)); + if solidcraft_render::RenderLimits::default().fit(size.0, size.1, None) != Some(size) { + return Err(bad("render.result.copy", "clipboard image exceeds 4096 per side or 4194304 pixels; export the PNG instead")); + } + Ok(json!({"frame":frame.info})) +} + +pub(super) fn cancel(s: &mut Session, params: &Value) -> Result { + let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; + let status = s.render_jobs.status(input.job).map_err(job_error)?; + if status.progress.phase.terminal() { + return Ok(json!(status)); + } + Ok(json!(s.render_jobs.handle(input.job).map_err(job_error)?.cancel().map_err(job_error)?)) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] +#[serde(rename_all = "snake_case")] +enum ExportFormat { + #[default] + Png, + Exr, +} +impl ExportFormat { + fn extension(self) -> &'static str { + match self { + Self::Png => "png", + Self::Exr => "exr", + } + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Export { + #[serde(default)] + format: ExportFormat, + job: JobId, + path: String, + #[serde(default)] + overwrite: bool, +} + +pub(super) fn export(s: &mut Session, params: &Value) -> Result { + let input: Export = serde_json::from_value(params.clone()).map_err(|e| bad("render.export", e.to_string()))?; + let path = std::path::Path::new(&input.path); + if input.path.len() > 4096 + || input.path.chars().any(char::is_control) + || !path.extension().is_some_and(|x| x.eq_ignore_ascii_case(input.format.extension())) + { + return Err(bad("render.export", "a bounded destination with the explicitly selected png/exr extension is required")); + } + // Atomic native writers are also used for the app's own files and do not + // apply a request's path scope. Check the caller's destination explicitly. + solidcraft_io::vfs::check(&input.path).map_err(|e| bad("render.export", e.to_string()))?; + let frame = s.render_jobs.frame(input.job).map_err(job_error)?; + let bytes = match input.format { + ExportFormat::Png => frame.png(), + ExportFormat::Exr => frame + .linear_exr() + .ok_or_else(|| bad("render.export", "this completed job has no raw linear master; enable retention before rendering"))?, + }; + // Replace atomically without reading an arbitrarily large previous target into memory. + // Design saves retain their independent backup policy. + let result = + if input.overwrite { solidcraft_io::write_atomic(path, bytes, false) } else { solidcraft_io::safe_write::create_atomic(path, bytes) }; + result.map_err(|e| bad("render.export", format!("could not export completed {}: {e}", input.format.extension())))?; + Ok( + json!({"job":input.job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), + ) +} + +fn validate_studio_weights(weights: Option<[f64; 3]>, command: &str) -> Result> { + if weights.is_some_and(|weights| weights.iter().any(|value| !value.is_finite() || !(0.0..=1.0).contains(value))) { + return Err(bad(command, "studio visibility weights must be finite in 0..1")); + } + Ok(weights) +} + +#[cfg(test)] +mod directional_shadow_guard_tests { + use super::*; + + fn wire() -> Value { + json!({"integrator":"raytrace","settings":{"width":1,"height":1,"job":null}, + "raytrace":{"directional_shadow_transmission":true,"shadows":true,"lights":[], + "dielectrics":[{"body_index":0,"body_name":"guard-only target","boundary":"thin_sheet", + "ior":1.0,"absorption_per_mm":[0.0,0.0,0.0],"thickness_mm":1.0}]}}) + } + + #[test] + fn interactive_lowering_preserves_real_directional_mode_without_selecting_it_by_default() { + for enabled in [false, true] { + let mut input = wire(); + input["raytrace"]["directional_shadow_transmission"] = json!(enabled); + let lowered = interactive_params(&input).unwrap(); + let after: Start = serde_json::from_value(lowered.clone()).unwrap(); + assert_eq!(after.raytrace.unwrap().directional_shadow_transmission, enabled); + assert_eq!(lowered["raytrace"].get("directional_shadow_transmission").and_then(Value::as_bool), enabled.then_some(true)); + } + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn directional_context_refusals_precede_unopened_hdr_and_product_capture() { + let mut session = Session::default(); + let host = solidcraft_render::job::CpuHost::for_platform().unwrap(); + session.set_render_job_host(Some(host)).unwrap(); + for nested in [false, true] { + let mut input = wire(); + if nested { + input["nested_media"] = json!(true); + } else { + input["environment"] = json!({"path":"must-not-open-original-directional.hdr","samples":4}); + } + let error = prepare(&session, &input, "render.start").err().unwrap().to_string(); + assert!( + error.contains(if nested { + "directional shadow transmission does not support nested media" + } else { + "directional shadow transmission does not support HDR environments" + }), + "{error}" + ); + assert!(!error.contains("could not read")); + assert_eq!(session.render_job_host().unwrap().admitted_bytes(), 0); + } + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/render_jobs.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/render_jobs.rs new file mode 100644 index 000000000..ca9ddea83 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/engine/src/render_jobs.rs @@ -0,0 +1,861 @@ +//! Per-document, transient render ownership. Captured scenes remain immutable when CAD edits +//! continue; callers get the captured revision and must never present it as a newer scene. + +use crate::render_interactive::{Controller, InteractiveRender, with_controller}; +use solidcraft_render::{ + ExecutorDescriptor, + job::{CpuHost, ErrorCode, HostKind, Integrator, JobError, JobHandle, JobId, JobStatus, Phase, RenderFrame}, +}; +use std::collections::VecDeque; +use std::sync::{ + Arc, Weak, + atomic::{AtomicU64, Ordering}, +}; + +static NEXT_OWNER: AtomicU64 = AtomicU64::new(1); + +/// The native CPU worker has two explicit execution methods. This pure metadata +/// lookup neither creates a host nor enables raytracing in cooperative/feature-off builds. +/// A stopped native host keeps its descriptor, marked unavailable by the host. +pub(crate) fn cpu_raytrace_descriptor(host: Option<&CpuHost>) -> Option { + let host = host.filter(|host| host.kind() == HostKind::NativeWorker)?; + host.descriptor_for(Integrator::Raytrace).ok() +} + +fn owner() -> u64 { + let mut n = NEXT_OWNER.load(Ordering::Relaxed); + loop { + let Some(next) = n.checked_add(1) else { return 0 }; + match NEXT_OWNER.compare_exchange_weak(n, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return n, + Err(current) => n = current, + } + } +} + +pub(crate) struct Execution { + pub executor: solidcraft_render::ExecutorId, + pub options: solidcraft_render::job::JobOptions, + pub environment: Option, +} + +pub(crate) struct Jobs { + owner: u64, + serial: u64, + generation: u64, + pub(crate) host: Option, + pub(crate) descriptor: Option, + pub(crate) additional: Vec<(CpuHost, ExecutorDescriptor)>, + live: Vec, + history: VecDeque, + last_good: Option, + /// One explicitly displayed completed result, independent of a newer completion. + /// The existing frame Arc keeps its original host reservation accounted for. + pinned: Option, + /// Preview lifetime only; it never joins final live/history/export ownership. + interactive: Weak, +} + +impl Default for Jobs { + fn default() -> Self { + Self { + owner: owner(), + serial: 0, + generation: 0, + host: None, + descriptor: None, + additional: Vec::new(), + live: Vec::new(), + history: VecDeque::new(), + last_good: None, + pinned: None, + interactive: Weak::new(), + } + } +} + +impl Drop for Jobs { + fn drop(&mut self) { + let _ = self.revoke_interactive(); + for job in &self.live { + let _ = job.cancel(); + } + } +} + +impl Jobs { + pub(crate) fn is_interactive_current(&self, controller: &Weak) -> bool { + Weak::ptr_eq(&self.interactive, controller) + } + + fn revoke_interactive(&mut self) -> Result<(), JobError> { + let previous = std::mem::take(&mut self.interactive); + match previous.upgrade() { + Some(controller) => with_controller(&controller, |state| state.disable()), + None => Ok(()), + } + } + + fn suspend_interactive(&self) -> Result<(), JobError> { + match self.interactive.upgrade() { + Some(controller) => with_controller(&controller, |state| state.set_final_active(true, std::time::Duration::ZERO)), + None => Ok(()), + } + } + + fn final_active(&self) -> Result { + for job in &self.live { + if !job.status()?.progress.phase.terminal() { + return Ok(true); + } + } + Ok(false) + } + + fn create_interactive(&mut self, document_uid: u64) -> Result { + let host = self.host.as_ref().ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "no CPU image host is installed"))?; + if !host.is_available() || host.kind() != HostKind::NativeWorker { + return Err(JobError::new(ErrorCode::HostUnavailable, "Interactive CPU requires an available native CPU host")); + } + host.validate_integrator(Integrator::Raytrace)?; + let final_active = self.final_active()?; + if document_uid == 0 || self.owner == 0 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render session identity exhausted")); + } + // Use the same allocator as final owners; never reuse the document uid or + // scratch owner as a preview namespace. Zero reports allocator exhaustion. + let preview_session = owner(); + if preview_session == 0 { + return Err(JobError::new(ErrorCode::LimitExceeded, "Interactive owner identity exhausted")); + } + let next = InteractiveRender::new(document_uid, preview_session, final_active)?; + self.revoke_interactive()?; + self.interactive = next.weak(); + Ok(next) + } + + pub(crate) fn host_for(&self, executor: &solidcraft_render::ExecutorId) -> Option<&CpuHost> { + if executor.as_str() == "cpu-raytrace" { + return self + .host + .as_ref() + .filter(|host| host.descriptor_for(solidcraft_render::job::Integrator::Raytrace).is_ok_and(|d| &d.id == executor)); + } + if self.descriptor.as_ref().is_some_and(|d| &d.id == executor) { + return self.host.as_ref(); + } + self.additional.iter().find(|(_, d)| &d.id == executor).map(|(host, _)| host) + } + + pub(crate) fn scratch(&self) -> Self { + let mut jobs = Self::default(); + jobs.host = self.host.clone(); + jobs.descriptor = self.descriptor.clone(); + jobs.additional = self.additional.clone(); + jobs + } + + pub(crate) fn collect(&mut self) -> Result<(), JobError> { + let mut i = 0; + while i < self.live.len() { + let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.status()?; + if !status.progress.phase.terminal() { + i += 1; + continue; + } + let handle = self.live.remove(i); + if status.progress.phase == Phase::Completed && self.last_good.as_ref().is_none_or(|old| old.id().serial < handle.id().serial) { + self.last_good = Some(handle); + } + self.history.push_back(status); + while self.history.len() > 4 { + self.history.pop_front(); + } + } + Ok(()) + } + + pub(crate) fn start_with_environment( + &mut self, + revision: u64, + scene: solidcraft_render::ProductScene, + request: solidcraft_render::job::ImageRequest, + replace: bool, + execution: Execution, + ) -> Result { + self.start_with_environment_and_feedback(revision, scene, request, replace, execution, false) + } + + pub(crate) fn start_with_environment_and_feedback( + &mut self, + revision: u64, + scene: solidcraft_render::ProductScene, + request: solidcraft_render::job::ImageRequest, + replace: bool, + execution: Execution, + progressive_feedback: bool, + ) -> Result { + if progressive_feedback + && (request.integrator != Integrator::Raytrace || request.raytrace.as_ref().and_then(|options| options.progressive).is_none()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "progressive_feedback requires CPU progressive raytracing")); + } + let Execution { executor, options, environment } = execution; + self.collect()?; + let host = self.host_for(&executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone(); + if replace { + for job in self.live.drain(..) { + let mut status = job.cancel()?; + // Replaced handles are deliberately abandoned: keep a cancellation tombstone, + // not a permanently "cancelling" snapshot. The token already prevents any + // publication; the host can finish releasing its buffers asynchronously. + if !status.progress.phase.terminal() { + status.progress.phase = Phase::Cancelled; + } + self.history.push_back(status); + } + while self.history.len() > 4 { + self.history.pop_front(); + } + } + if self.live.len() >= 2 { + return Err(JobError::new(ErrorCode::QueueFull, "this document already has an active and pending render")); + } + if self.owner == 0 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render session identity exhausted")); + } + let serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render job identity exhausted"))?; + let generation = self.generation.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render generation exhausted"))?; + self.suspend_interactive()?; + let id = JobId { session: self.owner, serial, generation }; + let handle = if progressive_feedback { + host.submit_cpu_protected_partial_with_environment_and_options(id, revision, scene, request, options, environment)? + } else { + host.submit_with_environment_and_options(id, revision, scene, request, options, environment)? + }; + let status = handle.status()?; + self.serial = serial; + self.generation = generation; + self.live.push(handle); + Ok(status) + } + + pub(crate) fn regrade( + &mut self, + source_id: JobId, + presentation: solidcraft_render::job::presentation::Presentation, + ) -> Result { + presentation.validate()?; + self.collect()?; + let source = self.handle(source_id)?; + let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; + let master = frame.master_source()?; + // Prefer the source pool so its retained source and derivative work share + // one admission authority. Regrading itself never invokes its executor. + let host = self + .host_for(&master.info.executor) + .or(self.host.as_ref()) + .ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "no image host is installed for master presentation"))? + .clone(); + if self.live.len() >= 2 { + return Err(JobError::new(ErrorCode::QueueFull, "this document already has an active and pending render")); + } + let serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render job identity exhausted"))?; + let generation = self.generation.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "render generation exhausted"))?; + if self.owner == 0 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render session identity exhausted")); + } + self.suspend_interactive()?; + let handle = host.submit_regrade(JobId { session: self.owner, serial, generation }, &source, presentation)?; + let status = handle.status()?; + self.serial = serial; + self.generation = generation; + self.live.push(handle); + Ok(status) + } + + fn check_owner(&self, id: JobId) -> Result<(), JobError> { + if id.session != self.owner { + return Err(JobError::new(ErrorCode::WrongOwner, "render job belongs to another document session")); + } + Ok(()) + } + + pub(crate) fn handle(&self, id: JobId) -> Result { + self.check_owner(id)?; + self.live + .iter() + .chain(self.last_good.iter()) + .chain(self.pinned.iter()) + .find(|j| j.id() == id) + .cloned() + .ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) + } + + pub(crate) fn status(&mut self, id: JobId) -> Result { + self.check_owner(id)?; + self.collect()?; + if let Ok(handle) = self.handle(id) { + return handle.status(); + } + self.history.iter().find(|s| s.job == id).cloned().ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) + } + + pub(crate) fn pin(&mut self, id: Option) -> Result, JobError> { + let Some(id) = id else { + self.pinned = None; + return Ok(None); + }; + let handle = self.handle(id)?; + let frame = handle.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "only a completed result can be pinned"))?; + let info = frame.info.clone(); + self.pinned = Some(handle); + Ok(Some(info)) + } + + pub(crate) fn frame(&mut self, id: JobId) -> Result, JobError> { + self.collect()?; + self.handle(id)?.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "render has no completed image")) + } +} + +impl crate::Session { + /// Explicit activation support. The caller owns one app-wide capture worker. + /// This registers a lifetime only; it never captures or starts an image. + pub fn interactive_render(&mut self) -> crate::Result { + self.render_jobs.create_interactive(self.uid).map_err(job_error) + } + + /// Bounded final-job metadata for current/background document scheduling. + /// Retained completed images do not block Interactive; unknown status fails. + pub fn render_final_active(&self) -> crate::Result { + self.render_jobs.final_active().map_err(job_error) + } + + /// A host is installed by the application, never by document data or a command. + pub fn set_render_job_host(&mut self, host: Option) -> crate::Result<()> { + if self.render_jobs.host.as_ref().zip(host.as_ref()).is_some_and(|(a, b)| a.same_host(b)) { + return Ok(()); + } + let descriptor = host.as_ref().map(CpuHost::descriptor).transpose().map_err(job_error)?; + if descriptor.as_ref().is_some_and(|d| d.id.as_str() == "cpu-raytrace") { + return Err(crate::EngineError::Other("cpu-raytrace is reserved for the native CPU raytrace integrator".into())); + } + let previous_raytrace = cpu_raytrace_descriptor(self.render_jobs.host.as_ref()); + let mut backend = self.render_backend(); + backend.executors.retain(|e| { + self.render_jobs.descriptor.as_ref().is_none_or(|old| old.id != e.id) && previous_raytrace.as_ref().is_none_or(|old| old.id != e.id) + }); + if let Some(d) = &descriptor { + backend.executors.push(d.clone()); + } + if let Some(raytrace) = cpu_raytrace_descriptor(host.as_ref()) { + backend.executors.push(raytrace); + } + solidcraft_render::resolve_request( + &[backend], + &solidcraft_render::RenderRequest { + backend: None, + mode: solidcraft_render::RenderMode::Preview, + operation: solidcraft_render::RenderOperation::Image, + width: 1, + height: 1, + format: Some(solidcraft_render::RenderFormat::Png), + features: Vec::new(), + policy: Default::default(), + }, + ) + .map_err(|e| crate::EngineError::Other(e.to_string()))?; + let mut jobs = Jobs::default(); + jobs.additional = self.render_jobs.additional.clone(); + jobs.host = host; + jobs.descriptor = descriptor; + self.render_jobs = jobs; + Ok(()) + } + + /// Add an executor without replacing CPU jobs or their ownership. Applications share + /// this host across document sessions; descriptor IDs must be unique in the registry. + pub fn register_render_job_host(&mut self, host: solidcraft_render::job::ImageHost) -> crate::Result<()> { + let descriptor = host.descriptor().map_err(job_error)?; + if descriptor.id.as_str() == "cpu-raytrace" { + return Err(crate::EngineError::Other("cpu-raytrace is reserved for the native CPU raytrace integrator".into())); + } + if self.render_jobs.additional.iter().any(|(old, _)| old.same_host(&host)) { + return Ok(()); + } + if descriptor.profiles.iter().any(|p| p.operation != solidcraft_render::RenderOperation::Image) { + return Err(crate::EngineError::Other("image host must only register image profiles".into())); + } + let mut registry = self.render_backend(); + registry.executors.push(descriptor.clone()); + solidcraft_render::resolve_request( + &[registry], + &solidcraft_render::RenderRequest { + backend: None, + mode: solidcraft_render::RenderMode::Preview, + operation: solidcraft_render::RenderOperation::Image, + width: 1, + height: 1, + format: Some(solidcraft_render::RenderFormat::Png), + features: Vec::new(), + policy: Default::default(), + }, + ) + .map_err(|e| crate::EngineError::Other(e.to_string()))?; + self.render_jobs.additional.push((host, descriptor)); + Ok(()) + } + + pub fn render_job_host(&self) -> Option<&CpuHost> { + self.render_jobs.host.as_ref() + } + + /// Explicit native CLI waiting is separate from non-blocking status commands. + pub fn render_job_handle(&self, id: JobId) -> crate::Result { + self.render_jobs.handle(id).map_err(job_error) + } +} + +pub(crate) fn job_error(error: JobError) -> crate::EngineError { + crate::EngineError::Other(error.to_string()) +} + +#[cfg(test)] +mod displayed_result_tests { + use super::*; + use serde_json::json; + fn complete(s: &mut crate::Session, color: [u8; 3]) -> JobId { + let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8,"background":color}})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..10000 { + host.pump(16384).unwrap(); + if s.render_job_handle(id).unwrap().status().unwrap().progress.phase.terminal() { + return id; + } + } + panic!("bounded result fixture did not finish") + } + #[test] + fn explicit_display_pin_preserves_the_old_exact_frame_without_unbounded_history() { + let mut s = crate::Session::default(); + let host = CpuHost::cooperative(); + s.set_render_job_host(Some(host.clone())).unwrap(); + let before = s.doc.to_json(); + let undo = s.undo.len(); + let old = complete(&mut s, [10, 20, 30]); + let bytes = s.render_job_handle(old).unwrap().frame().unwrap().unwrap().png().to_vec(); + s.execute("render.result.pin", &json!({"job":old})).unwrap(); + for color in [[40, 50, 60], [70, 80, 90], [100, 110, 120], [130, 140, 150], [160, 170, 180]] { + let new = complete(&mut s, color); + s.execute("render.status", &json!({"job":new})).unwrap(); + assert_eq!(s.render_job_handle(old).unwrap().frame().unwrap().unwrap().png(), bytes); + } + let retained = host.admitted_bytes(); + let foreign = JobId { session: old.session + 1, ..old }; + assert!(s.execute("render.result.pin", &json!({"job":foreign})).is_err()); + assert_eq!(host.admitted_bytes(), retained); + assert!(s.execute("render.result.pin", &json!({})).is_err()); + s.execute("render.result.pin", &json!({"job":null})).unwrap(); + assert!(s.render_job_handle(old).is_err()); + assert!(host.admitted_bytes() < retained); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + assert!(s.execute("render.result.pin", &json!({"job":reply["job"]})).is_err(), "a pending result is never exportable"); + } +} + +// Original context ownership and real capture integration cases. +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod interactive_context_tests { + use super::*; + use crate::render_interactive::{InteractiveRender, Snapshot, adopt_created}; + use serde_json::{Value, json}; + use solidcraft_render::job::interactive::{State, VisualRevision}; + use std::time::Duration; + + fn native() -> crate::Result<(crate::Session, CpuHost)> { + let host = CpuHost::for_platform().map_err(job_error)?; + let mut session = crate::Session::default(); + session.set_render_job_host(Some(host.clone()))?; + Ok((session, host)) + } + + fn wire(background: [u8; 3]) -> Value { + json!({"integrator":"raytrace","settings":{"width":16,"height":16,"background":background},"raytrace":{"lights":[],"shadows":false}}) + } + + fn capture(context: &InteractiveRender, session: &crate::Session, request: &Value) -> crate::Result { + context.enable(VisualRevision { scene_generation: session.revision, visual_revision: 1 }, Duration::ZERO)?; + let ticket = context + .capture(Duration::from_millis(200))? + .ok_or_else(|| crate::EngineError::Other("interactive fixture did not produce a capture ticket".into()))?; + context.snapshot(session, ticket, request) + } + + fn terminal(job: &JobHandle) -> crate::Result { + // Completion watchdog follows existing native job tests; no speed assertion. + Ok(job.wait_timeout(Duration::from_secs(60)).map_err(job_error)?.progress.phase) + } + + fn created(session: &crate::Session, ticket: solidcraft_render::job::interactive::CaptureTicket, request: &Value) -> crate::Result { + let p = crate::cmd::prepare_interactive(session, request)?; + session + .render_job_host() + .ok_or_else(|| crate::EngineError::Other("interactive fixture has no render job host".into()))? + .submit_with_environment_and_options(ticket.job_id(), ticket.revision().scene_generation, p.scene, p.request, p.options, p.environment) + .map_err(job_error) + } + + #[test] + fn registration_is_explicit_and_preview_frames_never_join_final_registry() { + let (mut session, _) = native().unwrap(); + let document = session.doc.clone(); + let history = (session.revision, session.undo.len(), session.redo.len()); + let context = session.interactive_render().unwrap(); + assert_eq!(context.state().unwrap(), State::Off); + assert!(context.is_current(&session)); + assert!(context.capture(Duration::from_secs(1)).unwrap().is_none()); + let snapshot = capture(&context, &session, &wire([31, 67, 101])).unwrap(); + let ticket = snapshot.ticket(); + assert_ne!(ticket.job_id().session, session.render_jobs.owner); + assert_eq!(snapshot.document_uid(), session.uid); + assert!(snapshot.run().unwrap()); + let preview = context.current().unwrap().unwrap(); + assert_eq!(terminal(&preview).unwrap(), Phase::Completed); + assert!(preview.frame().unwrap().is_some()); + assert!(session.render_job_handle(preview.id()).is_err()); + assert!(session.execute("render.status", &json!({"job":preview.id()})).is_err()); + assert!(session.render_jobs.live.is_empty()); + assert!(session.render_jobs.last_good.is_none()); + assert!(session.render_jobs.pinned.is_none()); + assert_eq!(history, (session.revision, session.undo.len(), session.redo.len())); + assert!(Arc::ptr_eq(&document, &session.doc)); + } + + #[test] + fn direct_final_start_preempts_only_interactive_and_finishes() { + let (mut session, _) = native().unwrap(); + let context = session.interactive_render().unwrap(); + assert!(capture(&context, &session, &wire([11, 29, 47])).unwrap().run().unwrap()); + let old = context.current().unwrap().unwrap(); + let reply = session.execute("render.start", &wire([83, 107, 139])).unwrap(); + let final_id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + let final_job = session.render_job_handle(final_id).unwrap(); + assert_ne!(final_id.session, old.id().session); + assert_eq!(context.state().unwrap(), State::Paused); + assert!(context.current().unwrap().is_none()); + assert!(context.capture(Duration::from_secs(100)).unwrap().is_none()); + assert_eq!(terminal(&final_job).unwrap(), Phase::Completed); + assert!(matches!(terminal(&old).unwrap(), Phase::Cancelled | Phase::Completed)); + assert!(!session.render_final_active().unwrap()); + let digest = final_job.frame().unwrap().unwrap().info.png_sha256.clone(); + context.disable().unwrap(); + drop(context); + assert_eq!(session.render_job_handle(final_id).unwrap().frame().unwrap().unwrap().info.png_sha256, digest); + } + + #[test] + fn replacement_context_revokes_old_capture_without_meshing() { + let (mut session, host) = native().unwrap(); + session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Source"})).unwrap(); + let world = session.world_state(); + assert!(world.body("Source").unwrap().cached_mesh().is_none()); + let old = session.interactive_render().unwrap(); + let snapshot = capture(&old, &session, &wire([1, 2, 3])).unwrap(); + let old_owner = snapshot.ticket().job_id().session; + let fresh = session.interactive_render().unwrap(); + assert!(!old.is_current(&session)); + assert_eq!(old.state().unwrap(), State::Off); + assert_eq!(fresh.state().unwrap(), State::Off); + assert!(!snapshot.run().unwrap()); + assert!(world.body("Source").unwrap().cached_mesh().is_none()); + assert_eq!(host.admitted_bytes(), 0); + let next = capture(&fresh, &session, &wire([4, 5, 6])).unwrap(); + assert_ne!(next.ticket().job_id().session, old_owner); + } + + #[test] + fn host_a_b_a_cannot_revive_old_registration_in_the_same_document() { + let (mut session, host_a) = native().unwrap(); + let uid = session.uid; + let old = session.interactive_render().unwrap(); + let snapshot = capture(&old, &session, &wire([1, 2, 3])).unwrap(); + let host_b = CpuHost::for_platform().unwrap(); + session.set_render_job_host(Some(host_b)).unwrap(); + assert_eq!(session.uid, uid); + assert!(!old.is_current(&session)); + assert_eq!(old.state().unwrap(), State::Off); + assert!(!snapshot.run().unwrap()); + session.set_render_job_host(Some(host_a.clone())).unwrap(); + assert!(!old.is_current(&session)); + old.enable(VisualRevision { scene_generation: session.revision, visual_revision: 2 }, Duration::ZERO).unwrap(); + let stale = old.capture(Duration::from_millis(200)).unwrap().unwrap(); + assert!(old.snapshot(&session, stale, &wire([7, 8, 9])).is_err()); + assert_eq!(host_a.admitted_bytes(), 0); + assert!(session.interactive_render().unwrap().is_current(&session)); + } + + #[test] + fn new_design_and_equal_revision_foreign_session_refuse_old_tickets() { + let (mut session, host) = native().unwrap(); + let context = session.interactive_render().unwrap(); + let snapshot = capture(&context, &session, &wire([1, 2, 3])).unwrap(); + let ticket = snapshot.ticket(); + let uid = session.uid; + let mut foreign = crate::Session::new((*session.doc).clone()); + foreign.revision = session.revision; + foreign.set_render_job_host(Some(host.clone())).unwrap(); + assert_ne!(foreign.uid, uid); + assert!(!context.is_current(&foreign)); + assert!(context.snapshot(&foreign, ticket, &wire([4, 5, 6])).is_err()); + session.execute("file.new", &json!({})).unwrap(); + assert_ne!(session.uid, uid); + assert!(!context.is_current(&session)); + assert_eq!(context.state().unwrap(), State::Off); + assert!(!snapshot.run().unwrap()); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn scratch_drop_does_not_revoke_source_and_exhaustion_is_local() { + let (mut session, _) = native().unwrap(); + let context = session.interactive_render().unwrap(); + drop(session.scratch()); + assert!(context.is_current(&session)); + assert_eq!(context.state().unwrap(), State::Off); + assert!(InteractiveRender::new(session.uid, 0, false).is_err()); + let original_owner = session.render_jobs.owner; + session.render_jobs.owner = 0; + assert!(session.interactive_render().is_err()); + assert!(context.is_current(&session)); + session.render_jobs.owner = original_owner; + } + + #[test] + fn failed_adoption_with_poisoned_controller_cancels_unpumped_cooperative_record() { + let (mut session, _) = native().unwrap(); + let context = session.interactive_render().unwrap(); + let snapshot = capture(&context, &session, &wire([1, 2, 3])).unwrap(); + let ticket = snapshot.ticket(); + let p = crate::cmd::prepare_interactive(&session, &wire([1, 2, 3])).unwrap(); + let mut request = p.request; + request.integrator = Integrator::Raster; + request.raytrace = None; + // A real cooperative queue cannot complete without an explicit pump. + // Adoption checks owner, then the poisoned lifecycle before integrator. + let cooperative = CpuHost::cooperative(); + let job = cooperative.submit(ticket.job_id(), ticket.revision().scene_generation, p.scene, request).unwrap(); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + let controller = session.render_jobs.interactive.upgrade().unwrap(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _guard = controller.lock().unwrap(); + panic!("original poison fixture"); + })); + assert!(adopt_created(&controller, ticket, job.clone()).is_err()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(context.current().is_err(), "a poisoned lifecycle is not resumed"); + // No pump, sleeps, synthetic executor or large scene is needed. Removing + // Unadopted::drop cancellation leaves Queued and fails this assertion. + // Only controller poison is tested; record.data poison is best-effort. + } + + #[test] + fn rejected_fresh_equal_id_record_preserves_retained_completed_frame() { + let (mut session, _) = native().unwrap(); + let context = session.interactive_render().unwrap(); + let snapshot = capture(&context, &session, &wire([17, 31, 59])).unwrap(); + let ticket = snapshot.ticket(); + assert!(snapshot.run().unwrap()); + let accepted = context.current().unwrap().unwrap(); + assert_eq!(terminal(&accepted).unwrap(), Phase::Completed); + let frame = accepted.frame().unwrap().unwrap(); + let digest = frame.info.png_sha256.clone(); + let duplicate = created(&session, ticket, &wire([83, 107, 139])).unwrap(); + assert_eq!(duplicate.id(), accepted.id()); + let controller = session.render_jobs.interactive.upgrade().unwrap(); + assert!(!adopt_created(&controller, ticket, duplicate.clone()).unwrap()); + let phase = duplicate.status().unwrap().progress.phase; + assert!(phase.terminal() || phase == Phase::Cancelling); + assert!(matches!(terminal(&duplicate).unwrap(), Phase::Cancelled | Phase::Completed)); + let retained = context.current().unwrap().unwrap().frame().unwrap().unwrap(); + assert!(Arc::ptr_eq(&retained, &frame)); + assert_eq!(retained.info.png_sha256, digest); + // This native fixture proves accepted-record retention only. Completed + // duplicate work does not prove a cancellation request; core queued + // distinct-record acceptance covers that separate invariant. + assert_eq!(accepted.status().unwrap().request.background, [17, 31, 59]); + } + + #[test] + fn dropping_context_before_worker_start_keeps_the_source_mesh_cold() { + let (mut session, host) = native().unwrap(); + session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Source"})).unwrap(); + let world = session.world_state(); + assert!(world.body("Source").unwrap().cached_mesh().is_none()); + let context = session.interactive_render().unwrap(); + let snapshot = capture(&context, &session, &wire([1, 2, 3])).unwrap(); + drop(context); + assert!(!snapshot.run().unwrap()); + assert!(world.body("Source").unwrap().cached_mesh().is_none()); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn final_cpu_feedback_preserves_full_request_owner_and_exact_final_pixels() { + let (mut session, host) = native().unwrap(); + assert_eq!(host.kind(), HostKind::NativeWorker); + let before = session.doc.to_json(); + let history = (session.revision, session.undo.len(), session.redo.len()); + let request = json!({ + "integrator":"raytrace", "settings":{"width":13,"height":7,"background":[17,89,203]}, + "raytrace":{"lights":[],"shadows":false,"primary_samples":1,"progressive":{"samples_per_pixel":9,"seed":83}} + }); + let mut baseline: Option> = None; + for feedback in [false, true] { + let mut params = request.clone(); + params["progressive_feedback"] = json!(feedback); + let checked = session.execute("render.preflight", ¶ms).unwrap(); + if feedback { + let captured: solidcraft_render::job::ImageRequest = serde_json::from_value(checked["request"].clone()).unwrap(); + let scene = solidcraft_render::ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }; + let admitted = host + .admit_cpu_protected_partial_with_environment_and_options(&scene, &captured, solidcraft_render::job::JobOptions::default(), None) + .unwrap(); + assert_eq!(checked["admission"], serde_json::to_value(admitted).unwrap(), "Check uses the same authoritative protected admission"); + } + let started = session.execute("render.start", ¶ms).unwrap(); + let job: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + assert_eq!(job.session, session.render_jobs.owner); + let handle = session.render_job_handle(job).unwrap(); + assert_eq!(serde_json::to_value(handle.status().unwrap().request).unwrap(), checked["request"]); + assert_eq!(terminal(&handle).unwrap(), Phase::Completed); + let status = handle.status().unwrap(); + assert_eq!((status.request.width, status.request.height), (13, 7)); + let options = status.request.raytrace.as_ref().unwrap().progressive.unwrap(); + assert_eq!((options.samples_per_pixel, options.seed), (9, 83)); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (13, 7)); + assert!(image.pixels().all(|pixel| pixel.0 == [17, 89, 203, 255]), "independent constant-background miss oracle"); + if let Some(bytes) = &baseline { + assert_eq!(frame.png(), bytes.as_slice()); + } else { + baseline = Some(frame.png().to_vec()); + } + let report = handle.protected_preview_report().unwrap(); + assert_eq!(report.is_some(), feedback); + if let Some(report) = report { + assert_eq!(report.quota_limit, 64); + assert!(report.ordinary_used <= report.ordinary_limit); + assert!(report.presentation_used <= report.presentation_limit); + assert_eq!(report.quota_exhausted, report.accepted_snapshots == report.quota_limit); + } + assert!(!handle.request_partial_preview().unwrap(), "terminal demand cannot restart work"); + let foreign = JobId { session: job.session + 1, ..job }; + assert!(session.render_job_handle(foreign).is_err()); + assert!(session.execute("render.result.pin", &json!({"job":foreign})).is_err()); + session.execute("render.result.pin", &json!({"job":job})).unwrap(); + } + assert_eq!(before, session.doc.to_json()); + assert_eq!(history, (session.revision, session.undo.len(), session.redo.len())); + } + + #[test] + fn final_cpu_feedback_saved_normalization_and_legacy_omission_are_explicit() { + let (mut session, _) = native().unwrap(); + let typed = json!({"settings":{"width":13,"height":7,"background":[17,89,203], + "job":{"method":"cpu_raytrace","options":{"primary_samples":1,"lights":[],"shadows":false, + "progressive":{"samples_per_pixel":9,"seed":83}}}}}); + for feedback in [None, Some(false), Some(true)] { + let mut params = typed.clone(); + if let Some(feedback) = feedback { + params["progressive_feedback"] = json!(feedback); + } + let checked = session.execute("render.preflight", ¶ms).unwrap(); + let started = session.execute("render.start", ¶ms).unwrap(); + let job: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = session.render_job_handle(job).unwrap(); + assert_eq!(terminal(&handle).unwrap(), Phase::Completed); + assert_eq!(serde_json::to_value(handle.status().unwrap().request).unwrap(), checked["request"]); + assert_eq!(handle.protected_preview_report().unwrap().is_some(), feedback == Some(true)); + } + for mut invalid in + [json!({"settings":{"width":13,"height":7}}), wire([17, 89, 203]), json!({"progressive":true,"settings":{"width":13,"height":7}})] + { + invalid["progressive_feedback"] = json!(true); + for command in ["render.preflight", "render.start"] { + let error = session.execute(command, &invalid).unwrap_err().to_string(); + assert!(error.contains("progressive_feedback"), "{error}"); + } + } + let mut malformed = typed; + malformed["progressive_feedback"] = json!("true"); + assert!(session.execute("render.preflight", &malformed).is_err()); + } + + #[test] + fn final_cpu_protected_admission_accounts_captured_hdr_once_and_runs_real_host() { + use solidcraft_render::job::{CpuProgressiveOptions, ImageRequest, JobOptions, RaytraceOptions}; + let (session, host) = native().unwrap(); + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + integrator: Integrator::Raytrace, + width: 13, + height: 7, + background: [17, 89, 203], + raytrace: Some(RaytraceOptions { + lights: Some(Vec::new()), + shadows: false, + primary_samples: 1, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 9, seed: 83 }), + ..Default::default() + }), + studio_weights: None, + environment: None, + textures: None, + camera: Default::default(), + transparent_background: false, + }; + let scene = solidcraft_render::ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }; + // Original equirectangular 2x1 RGBE source: two distinct texels, eight payload bytes. + 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 1 +X 2\n".to_vec(); + bytes.extend_from_slice(&[96, 64, 32, 129, 32, 64, 96, 129]); + let encoded_capacity = bytes.capacity() as u64; + // Independent allocation contract: 2 RGB f32 texels = 24 bytes, one + // 2-pixel RGBE scanline = 8 bytes, plus the fixed 8192-byte task envelope. + let expected_hdr_bytes = encoded_capacity + 24 + 8 + 8192; + let source = solidcraft_render::lighting::HdrSource::new(bytes).unwrap(); + assert_eq!((source.info().width, source.info().height), (2, 1)); + assert_eq!(source.retained_encoded_bytes(), encoded_capacity); + assert_eq!(source.info().decoded_rgb_bytes, 24); + let environment = solidcraft_render::lighting::environment_input::EnvironmentInput::new(source, 0.25, 0.5, 1).unwrap(); + let plain = host.admit_cpu_protected_partial_with_environment_and_options(&scene, &request, JobOptions::default(), None).unwrap(); + let lit = host.admit_cpu_protected_partial_with_environment_and_options(&scene, &request, JobOptions::default(), Some(&environment)).unwrap(); + assert_eq!(environment.required_bytes().unwrap(), expected_hdr_bytes); + assert_eq!(lit.preparation_bytes - plain.preparation_bytes, expected_hdr_bytes); + assert_eq!( + lit.estimated_total_bytes - plain.estimated_total_bytes, + expected_hdr_bytes + std::mem::size_of::() as u64 + ); + let job = host + .submit_cpu_protected_partial_with_environment_and_options( + JobId { session: session.render_jobs.owner, serial: 1, generation: 1 }, + session.revision, + scene, + request, + JobOptions::default(), + Some(environment), + ) + .unwrap(); + assert_eq!(terminal(&job).unwrap(), Phase::Completed); + assert!(job.status().unwrap().environment.is_some()); + assert!(job.protected_preview_report().unwrap().is_some()); + assert_eq!(job.frame().unwrap().unwrap().info.width, 13); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/gpu/src/path/denoise_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/gpu/src/path/denoise_tests.rs new file mode 100644 index 000000000..888d3a377 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/gpu/src/path/denoise_tests.rs @@ -0,0 +1,354 @@ +use super::super::{Executor, JobOptions, Task, open_headless}; +use super::*; +use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_render::{ + Camera, ProductMesh, ProductScene, StandardView, + job::{CancelToken, ImageRequest, ImageWork, TaskPoll}, + surface::OpaqueSurface, +}; +use std::sync::Arc; + +type Guide = [[f64; 4]; 3]; +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a.into_iter().zip(b).map(|(x, y)| x * y).sum() +} +fn diff(a: [f64; 4], b: [f64; 4]) -> [f64; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} +fn xyz(a: [f64; 4]) -> [f64; 3] { + [a[0], a[1], a[2]] +} + +// Independent f64 gather oracle: all inputs are averaged linear values, so the +// GPU's accumulated-sample scaling is absent from this numerical implementation. +fn reference(width: usize, input: &[[f64; 4]], guides: &[Guide], step: usize) -> Vec<[f64; 4]> { + let height = input.len() / width; + let kernel = [1.0, 4.0, 6.0, 4.0, 1.0]; + input + .iter() + .enumerate() + .map(|(i, ¢er)| { + let [a, n, p] = guides[i]; + if a[3] == 0.0 || center[3] < 0.999 { + return center; + } + let mut result = [0.0; 4]; + let mut total = 0.0; + for (ky, &wy) in kernel.iter().enumerate() { + for (kx, &wx) in kernel.iter().enumerate() { + let x = (i % width) as isize + (kx as isize - 2) * step as isize; + let y = (i / width) as isize + (ky as isize - 2) * step as isize; + if x < 0 || y < 0 || x >= width as isize || y >= height as isize { + continue; + } + let j = y as usize * width + x as usize; + let [b, m, q] = guides[j]; + let value = input[j]; + if a[3] != b[3] || (value[3] - center[3]).abs() > 0.01 { + continue; + } + let albedo = diff(a, b); + let position = diff(q, p); + let plane = dot(position, xyz(n)).abs() + dot(position, xyz(m)).abs(); + let scale = (0.05 * p[3].max(q[3]) * step as f64).max(1e-6); + let depth = (n[3] - m[3]).abs() / (8.0 * p[3].max(q[3]) * step as f64).max(1e-6); + let color = diff(center, value); + let maximum = |v: [f64; 3]| v.into_iter().fold(0.0, f64::max); + let color_scale = 0.25 + 0.5 * maximum(xyz(center)).max(maximum(xyz(value))); + let weight = wx + * wy + * (-dot(albedo, albedo) / 0.04 - plane / scale - depth - maximum(color.map(f64::abs)) / color_scale).exp() + * dot(xyz(n), xyz(m)).max(0.0).powi(32); + for k in 0..3 { + result[k] += value[k] * weight; + } + total += weight; + } + } + for v in result.iter_mut().take(3) { + *v /= total; + } + result[3] = center[3]; + result + }) + .collect() +} +fn guide(x: usize, y: usize) -> Guide { + [[0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 1.0, 4.0], [x as f64, y as f64, 0.0, 1.0]] +} +fn fixture(size: usize) -> (Vec<[f64; 4]>, Vec) { + let mut pixels = Vec::new(); + let mut guides = Vec::new(); + for y in 0..size { + for x in 0..size { + // Deterministic white noise in [0.4, 0.6]. A pixel-frequency checker would + // be invisible to the step-2 and step-4 passes, which only reach same-parity pixels. + let hash = ((x * 7919 + y * 104_729) as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 40; + let level = 0.4 + 0.2 * hash as f64 / f64::from(1u32 << 24); + pixels.push([level, level, level, 1.0]); + guides.push(guide(x, y)); + } + } + (pixels, guides) +} +#[test] +fn f64_atrous_reduces_flat_noise_preserves_constant_and_coverage() { + let (input, guides) = fixture(17); + let mut result = input.clone(); + for step in [1, 2, 4] { + result = reference(17, &result, &guides, step); + } + let variance = |image: &[[f64; 4]]| { + let mean = image.iter().map(|p| p[0]).sum::() / image.len() as f64; + image.iter().map(|p| (p[0] - mean).powi(2)).sum::() / image.len() as f64 + }; + println!("noise variance {} -> {}", variance(&input), variance(&result)); + assert!(variance(&result) < variance(&input) / 4.0, "noise variance {} -> {}", variance(&input), variance(&result)); + assert_eq!(reference(17, &vec![[0.7, 0.3, 0.1, 0.5]; 289], &guides, 1), vec![[0.7, 0.3, 0.1, 0.5]; 289]); + let constant = reference(17, &vec![[0.75, 0.75, 0.75, 1.0]; 289], &guides, 4); + assert!(constant.iter().all(|p| p[..3].iter().all(|x| (*x - 0.75).abs() < 1e-14))); +} +#[test] +fn f64_atrous_preserves_body_normal_depth_and_albedo_edges() { + for edge in 0..5 { + let mut pixels = Vec::new(); + let mut guides = Vec::new(); + for y in 0..17 { + for x in 0..17 { + let mut g = guide(x, y); + let c = if x < 8 { 0.0 } else { 1.0 }; + if x >= 8 { + match edge { + 0 => g[0][3] = 2.0, + 1 => g[1] = [1.0, 0.0, 0.0, 4.0], + 2 => g[2][2] = 10.0, + 4 => g[1][3] = 1004.0, + _ => g[0] = [1.0, 1.0, 1.0, 1.0], + } + } + if edge == 3 && x < 8 { + g[0] = [0.0, 0.0, 0.0, 1.0]; + } + pixels.push([c, c, c, 1.0]); + guides.push(g); + } + } + let mut filtered = pixels.clone(); + for step in [1, 2, 4] { + filtered = reference(17, &filtered, &guides, step); + } + assert!(filtered.iter().zip(&pixels).all(|(a, b)| (a[0] - b[0]).abs() < 1e-12), "edge {edge}"); + } +} +fn context() -> Option> { + let (_, device, queue) = match open_headless() { + Ok(v) => v, + Err(e) => { + // The path tracer runs on Vulkan or Metal only: where the backends in use leave both out + // (`WGPU_BACKEND=dx12`), it is unavailable by design, not missing. + let available = !crate::select::path_backends().is_empty(); + assert!(!available || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}"); + return None; + } + }; + Some(Executor::new(device, queue).unwrap().context) +} +fn request(size: u32) -> ImageRequest { + let mut camera = Camera { distance: 4.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Default::default(), + raytrace: None, + camera, + width: size, + height: size, + background: [0; 3], + transparent_background: false, + environment: None, + textures: None, + } +} +fn plane() -> ProductScene { + let mesh = Mesh { + positions: vec![Vec3::new(-1.0, -1.0, 0.0), Vec3::new(1.0, -1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(-1.0, 1.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![ProductMesh { + name: "original denoise plane".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0.0, 1.0, 1.5).unwrap()), + transmission: None, + faces: Vec::new(), + }], + } +} +fn read_guides(context: &Context, buffer: &wgpu::Buffer) -> Vec<[f32; 4]> { + let staging = context.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: buffer.size(), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = context.device.create_command_encoder(&Default::default()); + encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, buffer.size()); + let submission = context.queue.submit([encoder.finish()]); + let (tx, rx) = std::sync::mpsc::channel(); + staging.slice(..).map_async(wgpu::MapMode::Read, move |v| { + tx.send(v).unwrap(); + }); + context.device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: Some(TIMEOUT) }).unwrap(); + rx.recv().unwrap().unwrap(); + let mapped = staging.slice(..).get_mapped_range().unwrap(); + let values = mapped.as_chunks::<16>().0.iter().map(|v| [0, 4, 8, 12].map(|i| f32::from_le_bytes(v[i..i + 4].try_into().unwrap()))).collect(); + drop(mapped); + staging.unmap(); + values +} +#[test] +fn denoise_admission_counts_guides_and_ping_pong_only_when_enabled() { + let scene = plane(); + let request = request(32); + let plain = super::super::admission(&scene, &request, JobOptions::default()).unwrap(); + let filtered = super::super::admission(&scene, &request, JobOptions { denoise: true, ..Default::default() }).unwrap(); + assert_eq!(filtered.pixel_scratch_bytes - plain.pixel_scratch_bytes, 32 * 32 * 80); + assert_eq!(filtered.estimated_total_bytes - plain.estimated_total_bytes, 32 * 32 * 80); + let large = ImageRequest { width: 2000, height: 2000, ..request.clone() }; + assert!(super::super::admission(&scene, &large, JobOptions::default()).is_ok()); + // The production envelope deliberately admits this former 512 MiB refusal. + // Still charge the guides/ping-pong in full, and reject outside the new edge. + let large_plain = super::super::admission(&scene, &large, JobOptions::default()).unwrap(); + let large_filtered = super::super::admission(&scene, &large, JobOptions { denoise: true, ..Default::default() }).unwrap(); + assert_eq!(large_filtered.pixel_scratch_bytes - large_plain.pixel_scratch_bytes, 2000 * 2000 * 80); + assert!(large_filtered.estimated_total_bytes > 512 * 1024 * 1024); + assert!(large_filtered.estimated_total_bytes <= solidcraft_render::job::GPU_PATH_LIMITS.max_scratch_bytes); + let excessive = ImageRequest { width: (solidcraft_render::job::GPU_PATH_LIMITS.max_dimension + 1) as u32, ..request.clone() }; + for denoise in [false, true] { + assert!(super::super::admission(&scene, &excessive, JobOptions { denoise, ..Default::default() }).is_err()); + } + assert!(!serde_json::from_str::("{}").unwrap().denoise); + assert!(serde_json::from_str::(r#"{"denoise":"true"}"#).is_err()); +} +#[test] +fn gpu_atrous_matches_f64_guides_and_leaves_input_unchanged() { + let Some(context) = context() else { + return; + }; + let (mut input, mut guides) = fixture(13); + for y in 0..13 { + for x in 7..13 { + guides[y * 13 + x][0][3] = 2.0; + input[y * 13 + x][0] += 0.8; + } + } + guides[0][0][3] = 0.0; + input[1][3] = 0.5; + let bytes: Vec = input.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); + let device = &context.device; + let make = |label, bytes: &[u8]| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some(label), + contents: bytes, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + }) + }; + let raw = make("denoise fixture raw", &bytes); + let dummy = make("denoise unused geometry", &[0; 64]); + let mut task = Task::new(context.clone(), plane(), request(13), JobOptions::default(), CancelToken::default()).unwrap(); + task.sample = 1; + let filter = Resources::new(&context, &task.uniform, [&dummy, &dummy, &dummy, &dummy, &dummy], &raw, bytes.len() as u64).unwrap(); + let guide_bytes: Vec = guides.iter().flatten().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); + context.queue.write_buffer(&filter._guides, 0, &guide_bytes); + let before = task.read_linear_buffer(&raw).unwrap(); + filter.run_filter(&task).unwrap(); + assert_eq!(before, task.read_linear_buffer(&raw).unwrap()); + let actual = task.read_linear_buffer(filter.output()).unwrap(); + let mut expected = input; + for step in [1, 2, 4] { + expected = reference(13, &expected, &guides, step); + } + for (a, b) in actual.iter().zip(&expected) { + for (x, y) in a.iter().zip(b) { + assert!((f64::from(*x) - *y).abs() < 2e-5, "{a:?} vs {b:?}"); + } + } +} +#[test] +fn gpu_denoise_default_false_is_identical_and_true_preserves_raw() { + let Some(context) = context() else { + return; + }; + let mut outputs = Vec::new(); + let mut pngs = Vec::new(); + for options in [ + JobOptions { samples: 4, ..Default::default() }, + JobOptions { samples: 4, denoise: false, ..Default::default() }, + JobOptions { samples: 4, denoise: true, ..Default::default() }, + ] { + let mut task = Task::new(context.clone(), plane(), request(8), options, CancelToken::default()).unwrap(); + assert_eq!(task.denoiser.is_some(), options.denoise); + while task.sample < 4 { + task.complete_sample().unwrap(); + } + let raw = task.read_linear().unwrap(); + if let Some(filter) = &task.denoiser { + filter.run(&task).unwrap(); + assert_eq!(raw, task.read_linear().unwrap()); + let filtered = task.read_linear_buffer(filter.output()).unwrap(); + assert!(filtered.iter().all(|p| p.iter().all(|v| v.is_finite()))); + let guides = read_guides(&context, &filter._guides); + assert_eq!(guides[0], [0.0; 4]); + let center = (4 * 8 + 4) * 3; + assert_eq!(guides[center], [0.5, 0.5, 0.5, 1.0]); + assert_eq!(guides[center + 1], [0.0, 0.0, 1.0, 16.0]); + assert!((guides[center + 2][0] - 0.2).abs() < 1e-6); + assert!((guides[center + 2][1] + 0.2).abs() < 1e-6); + assert!((guides[center + 2][3] - 0.4).abs() < 1e-6); + } + outputs.push(raw); + for _ in 0..100 { + if let TaskPoll::Complete(png) = task.step(4096).unwrap() { + pngs.push(png); + break; + } + } + } + assert_eq!(outputs[0], outputs[1]); + assert_eq!(outputs[0], outputs[2]); + assert_eq!(pngs.len(), 3); + assert_eq!(pngs[0], pngs[1]); +} +#[test] +fn gpu_denoise_preflight_reports_limits_without_changing_document() { + let Some(context) = context() else { + return; + }; + let mut session = solidcraft_engine::Session::default(); + session.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + session.register_render_job_host(solidcraft_render::job::ImageHost::with_executor(Arc::new(Executor { context })).unwrap()).unwrap(); + session.execute("solid.box", &serde_json::json!({"length":2,"width":2,"height":1})).unwrap(); + let before = session.doc.to_json(); + let mut params = serde_json::json!({"progressive":true,"denoise":true,"settings":{"width":8,"height":8}}); + let reply = session.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(reply["options"]["denoise"], true); + assert_eq!(reply["denoising"]["passes"], 3); + assert_eq!(reply["denoising"]["raw_linear_accumulator_preserved"], true); + assert_eq!(before, session.doc.to_json()); + params["progressive"] = serde_json::json!(false); + assert!(session.execute("render.preflight", ¶ms).is_err()); + params["denoise"] = serde_json::json!(false); + let reply = session.execute("render.preflight", ¶ms).unwrap(); + assert!(reply.get("denoising").is_none()); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/gpu/src/path/tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/gpu/src/path/tests.rs new file mode 100644 index 000000000..6fc1691f2 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/gpu/src/path/tests.rs @@ -0,0 +1,3357 @@ +use super::*; +use solidcraft_geom::{Aabb3, Mesh}; +use solidcraft_render::{Camera, ProductMesh, StandardView, surface::OpaqueSurface}; + +fn executor() -> Option { + let (adapter, device, queue) = match open_headless() { + Ok(device) => device, + Err(e) => { + // The path tracer runs on Vulkan or Metal only: where the backends in use leave both out + // (`WGPU_BACKEND=dx12`), it is unavailable by design, not missing. + let available = !crate::select::path_backends().is_empty(); + assert!(!available || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}"); + eprintln!("gpu-path device test skipped: {e}"); + return None; + } + }; + eprintln!("gpu-path tests on {} ({:?}, {:?})", adapter.get_info().name, adapter.get_info().device_type, adapter.get_info().backend); + Some(Executor::new(device, queue).unwrap()) +} +fn request(size: u32) -> ImageRequest { + let mut camera = Camera { distance: 4.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Default::default(), + raytrace: None, + textures: None, + environment: None, + camera, + width: size, + height: size, + background: [10, 20, 30], + transparent_background: false, + } +} +fn sphere(surface: OpaqueSurface) -> ProductScene { + sphere_grid(surface, 48, 96) +} +fn sphere_grid(surface: OpaqueSurface, rows: u32, columns: u32) -> ProductScene { + sphere_section(surface, rows, columns, rows) +} +fn sphere_section(surface: OpaqueSurface, rows: u32, columns: u32, rings: u32) -> ProductScene { + // Original unit sphere, deliberately triangulated here rather than imported test data. + let mut mesh = Mesh::default(); + for i in 0..=rings { + let theta = f64::from(i) * std::f64::consts::PI / f64::from(rows); + for j in 0..=columns { + let phi = f64::from(j) * std::f64::consts::TAU / f64::from(columns); + let n = Vec3::new(theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos()); + mesh.positions.push(n); + mesh.normals.push(n); + } + } + for i in 0..rings { + for j in 0..columns { + let a = i * (columns + 1) + j; + let b = a + columns + 1; + mesh.triangles.extend([[a, b, a + 1], [a + 1, b, b + 1]]); + mesh.tri_face.extend([0, 0]); + } + } + let bounds = mesh.bounds(); + ProductScene { + meshes: vec![ProductMesh { + name: "original sphere".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(surface), + transmission: None, + faces: Vec::new(), + }], + bounds, + } +} +fn white() -> OpaqueSurface { + OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap() +} + +fn clear_glass() -> solidcraft_render::transmission::Transmission { + solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap() +} + +#[test] +fn volume_glass_requires_closed_outward_homogeneous_geometry() { + let mut glass = sphere(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + glass.meshes[0].transmission = Some(clear_glass()); + assert!(scene::flatten(&glass, Vec3::ZERO, &CancelToken::default()).is_ok()); + let mut open = glass.clone(); + let mesh = Arc::make_mut(&mut open.meshes[0].mesh); + mesh.triangles.remove(300); + mesh.tri_face.remove(300); + assert!(scene::flatten(&open, Vec3::ZERO, &CancelToken::default()).is_err()); + let mut inward = glass; + for t in &mut Arc::make_mut(&mut inward.meshes[0].mesh).triangles { + t.swap(1, 2); + } + assert!(scene::flatten(&inward, Vec3::ZERO, &CancelToken::default()).is_err()); + open.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, Some(0.1)).unwrap()); + assert!(scene::flatten(&open, Vec3::ZERO, &CancelToken::default()).is_ok()); +} + +#[test] +fn nested_and_overlapping_dielectric_bounds_are_rejected_before_upload() { + let mut outer = sphere(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + outer.meshes[0].transmission = Some(clear_glass()); + for shift in [0.0, 0.5] { + let mut inner = outer.meshes[0].clone(); + for p in &mut Arc::make_mut(&mut inner.mesh).positions { + *p = *p * 0.5 + Vec3::new(shift, 0.0, 0.0); + } + let mut scene = outer.clone(); + scene.meshes.push(inner); + assert!(scene::flatten(&scene, Vec3::ZERO, &CancelToken::default()).is_err()); + } +} + +#[test] +fn multiple_closed_shells_in_one_dielectric_body_are_rejected() { + let mut scene = sphere(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + scene.meshes[0].transmission = Some(clear_glass()); + let second = scene.meshes[0].mesh.clone(); + let mesh = Arc::make_mut(&mut scene.meshes[0].mesh); + let offset = mesh.positions.len() as u32; + mesh.positions.extend(second.positions.iter().map(|p| *p + Vec3::new(4.0, 0.0, 0.0))); + mesh.normals.extend(&second.normals); + mesh.triangles.extend(second.triangles.iter().map(|t| t.map(|i| i + offset))); + mesh.tri_face.extend(&second.tri_face); + let error = scene::flatten(&scene, Vec3::ZERO, &CancelToken::default()).err().unwrap(); + assert!(error.to_string().contains("one connected shell"), "{error}"); +} + +#[test] +fn gpu_exact_dielectric_matches_f64_fresnel() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("dielectric_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), sphere(white()), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + for (ni, nt) in [(1.0_f64, 1.0_f64), (1.0, 1.5), (1.5, 1.0), (1.0, 3.0)] { + for cosine in [0.0, 0.01, 0.5, (nt / ni).atan().cos(), 1.0] { + let mut params = vec![0; 64]; + scene::vector(&mut params, Vec3::new(cosine, ni, nt), 0.0); + params.resize(PARAMETER_BYTES, 0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let expected = solidcraft_render::transmission::fresnel(cosine, ni, nt).unwrap(); + for (a, b) in actual.iter().zip([expected.s, expected.p, expected.transmitted_cosine.unwrap_or(0.0)]) { + assert!((f64::from(*a) - b).abs() < 2e-5, "Fresnel {ni}->{nt} cos={cosine}: {a} != {b}"); + } + } + } +} + +#[test] +fn gpu_nonabsorbing_glass_sphere_white_furnace_conserves_radiance() { + let Some(executor) = executor() else { return }; + let mut scene = sphere(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + scene.meshes[0].transmission = Some(clear_glass()); + scene.meshes[0].opacity = 0.2; + let options = JobOptions { samples: 512, max_depth: 16, seed: 1948, ..Default::default() }; + let mut task = Task::new(executor.context.clone(), scene, request(16), options, CancelToken::default()).unwrap(); + task.environment = 1.0; + task.studio = 0.0; + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + for (index, pixel) in task.read_linear().unwrap().iter().enumerate() { + assert!((pixel[0] - 1.0).abs() < 0.025, "glass furnace pixel {index}: {pixel:?}"); + } +} + +#[test] +fn gpu_ball_lens_focus_uses_actual_mesh_intersections() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("lens_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut scene = sphere_grid(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap(), 128, 256); + scene.meshes[0].transmission = Some(clear_glass()); + let mut task = Task::new(context.clone(), scene, request(1), JobOptions::default(), CancelToken::default()).unwrap(); + for height in [0.01, 0.02, 0.03] { + let mut params = vec![0; 32]; + scene::vector(&mut params, Vec3::new(height, 0.0, 3.0), 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, -Vec3::Z, 1.5); // nR/(2(n-1)), measured from centre. + scene::vector(&mut params, Vec3::new(f64::from(task.epsilon), 0.0, 0.0), 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + assert_eq!(actual[3], 1.0); + assert!((actual[0] - 1.0).abs() < 5e-5 && (actual[1] - 1.0).abs() < 5e-5, "image-space focal spot at h={height}: {actual:?}"); + } +} + +#[test] +fn gpu_camera_inside_volume_fails_without_publishing_fake_radiance() { + let Some(executor) = executor() else { return }; + let mut scene = sphere(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + scene.meshes[0].transmission = Some(clear_glass()); + let mut request = request(1); + request.camera.distance = 0.1; + let mut task = Task::new(executor.context.clone(), scene.clone(), request.clone(), JobOptions::default(), CancelToken::default()).unwrap(); + task.complete_sample().unwrap(); + assert_eq!(task.read_linear().unwrap_err().code, ErrorCode::InvalidScene); + drop(task); + // Seed just below the 32-bit wrap: the next real failed path must carry + // into the high word, rather than clearing diagnostics and publishing black. + let mut task = Task::new(executor.context.clone(), scene, request, JobOptions::default(), CancelToken::default()).unwrap(); + let mut failures = [0; FAILURE_BYTES as usize]; + failures[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + task.context.queue.write_buffer(&task.failures, 0, &failures); + task.complete_sample().unwrap(); + let error = task.read_linear().unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("4294967296 of 1 paths"), "{error}"); +} + +#[test] +fn engine_preflight_keeps_cpu_alpha_and_routes_physical_glass_to_the_native_host() { + use serde_json::json; + let Some(executor) = executor() else { return }; + let mut s = solidcraft_engine::Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":2,"body_name":"Glass"})).unwrap(); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#c0e0ff","opacity":0.2})).unwrap(); + let cpu = s.execute("render.preflight", &json!({"settings":{"width":16,"height":16}})).unwrap(); + assert_eq!(cpu["refraction"], false); + assert_eq!(cpu["transparency"], "sorted_alpha_approximation"); + assert!(s.execute("render.preflight", &json!({"progressive":true,"settings":{"width":16,"height":16}})).is_err()); + s.register_render_job_host(ImageHost::with_executor(Arc::new(executor)).unwrap()).unwrap(); + let snapshot = s.doc.to_json(); + let mut params = json!({"progressive":true,"settings":{"width":16,"height":16}, + "raytrace":{"dielectrics":[{"body_index":0,"body_name":"Glass","ior":1.5,"absorption_per_mm":[0.1,0.02,0],"boundary":"closed_box","thickness_mm":0}]}}); + let gpu = s.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(gpu["refraction"], true); + assert_eq!(gpu["dielectric_boundaries"], json!(["thin_sheet", "closed_box", "closed_mesh"])); + assert_eq!(gpu["transparency"], "physical_transmission"); + assert_eq!(gpu["resolved"]["executor"], "gpu-path"); + params["settings"]["camera"] = json!(Camera { distance: 40.0, fov: 0.7, ..Default::default() }); + params["lens"] = json!({"aperture_radius_mm":0.5,"focus_distance_mm":40}); + let lens = s.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(lens["options"]["lens"]["aperture_radius_mm"], 0.5); + assert_eq!(snapshot, s.doc.to_json()); + params["progressive"] = json!(false); + assert!(s.execute("render.preflight", ¶ms).is_err()); + assert!(!solidcraft_engine::product_scene::extract(&s).unwrap().has_transmission()); +} + +#[test] +fn gpu_thin_lens_focus_and_defocus_match_geometric_oracle() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("camera_reference"), + compilation_options: Default::default(), + cache: None, + }); + for (yaw, pitch, roll) in [(0.0, 0.0, 0.0), (-0.45, 0.5, 0.7)] { + let mut request = request(2); + request.camera = Camera { distance: 12.0, fov: 0.7, yaw, pitch, roll, ..Default::default() }; + let camera = request.camera; + let lens = solidcraft_render::job::ThinLens { aperture_radius_mm: 0.4, focus_distance_mm: 9.0 }; + let options = JobOptions { lens: Some(lens), ..Default::default() }; + let mut task = Task::new(context.clone(), sphere(white()), request, options, CancelToken::default()).unwrap(); + let (right, up, back) = camera.basis(); + let eye = back * camera.distance; + for (ux, uy) in [(0.0_f64, 0.0_f64), (0.7, -0.6)] { + let focal = + eye + (right * ux + up * uy) * (camera.half_height() * lens.focus_distance_mm / camera.distance) - back * lens.focus_distance_mm; + for (radial, azimuth) in [(0.0_f64, 0.0_f64), (0.25, 0.125), (0.75, 0.625), (0.999, 0.999)] { + let mut params = task.parameters(1); + params.truncate(96); + scene::vector(&mut params, Vec3::new(ux, uy, radial), azimuth as f32); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let rays = task.read_linear().unwrap(); + let vec = |p: [f32; 4]| Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])); + let origin = vec(rays[0]) - Vec3::new(16.0, 16.0, 16.0); + let direction = vec(rays[1]) - Vec3::new(2.0, 2.0, 2.0); + let disk = (right * (azimuth * std::f64::consts::TAU).cos() + up * (azimuth * std::f64::consts::TAU).sin()) + * (radial.sqrt() * lens.aperture_radius_mm); + assert!((origin - eye - disk).len() < 3e-6); + let focus_hit = origin + direction * ((focal - origin).dot(back) / direction.dot(back)); + assert!((focus_hit - focal).len() < 5e-6, "focus {focus_hit:?} != {focal:?}"); + // At axial depth z, signed displacement from the pinhole hit is + // disk*(1-z/focus). Check both sides, including the flip beyond focus. + for depth in [4.5, 18.0] { + let centre = eye - back * depth; + let hit = origin + direction * ((centre - origin).dot(back) / direction.dot(back)); + let pinhole = eye + (focal - eye) * (depth / lens.focus_distance_mm); + assert!((hit - pinhole - disk * (1.0 - depth / lens.focus_distance_mm)).len() < 1e-5); + } + } + } + } +} + +#[test] +fn gpu_zero_aperture_is_bit_identical_and_lens_admission_is_explicit() { + let Some(executor) = executor() else { return }; + let mut request = request(16); + request.camera.fov = 0.7; + let render = |lens, fov| { + let options = JobOptions { samples: 8, lens, seed: 1948, ..Default::default() }; + let mut image = request.clone(); + image.camera.fov = fov; + let mut task = Task::new(executor.context.clone(), sphere(white()), image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + task.read_linear().unwrap() + }; + for fov in [0.0, 0.7] { + assert_eq!(render(None, fov), render(Some(solidcraft_render::job::ThinLens { aperture_radius_mm: 0.0, focus_distance_mm: 8.0 }), fov)); + } + let lens = Some(solidcraft_render::job::ThinLens { aperture_radius_mm: 0.3, focus_distance_mm: 4.0 }); + assert_eq!(render(lens, 0.7), render(lens, 0.7)); + request.camera.fov = 0.0; + assert!(admission(&sphere(white()), &request, JobOptions { lens, ..Default::default() }).is_err()); + request.camera.fov = 1e-100; + assert!(admission(&sphere(white()), &request, JobOptions { lens, ..Default::default() }).is_err()); +} + +#[test] +#[ignore = "manual glass transport evidence; set SOLIDCRAFT_GLASS_EVIDENCE to a PNG path"] +fn glass_transport_evidence() { + let Some(executor) = executor() else { return }; + let output = std::env::var("SOLIDCRAFT_GLASS_EVIDENCE").unwrap(); + let mut meshes = Vec::new(); + for (centre, radius, color) in + [(Vec3::new(-1.3, 0.0, 1.5), 1.5, Vec3::new(0.75, 0.94, 1.0)), (Vec3::new(2.0, 1.0, 1.0), 1.0, Vec3::new(1.0, 0.7, 0.35))] + { + let mut scene = sphere_grid(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap(), 96, 192); + let mut body = scene.meshes.remove(0); + for p in &mut Arc::make_mut(&mut body.mesh).positions { + *p = *p * radius + centre; + } + body.transmission = + Some(solidcraft_render::transmission::Transmission::new(Vec3::new(-color.x.ln(), -color.y.ln(), -color.z.ln()) / 5.0, None).unwrap()); + meshes.push(body); + } + for y in -16..16 { + for x in -16..16 { + let color = if (x + y) % 2 == 0 { Vec3::new(0.65, 0.7, 0.75) } else { Vec3::new(0.035, 0.055, 0.08) }; + let x = f64::from(x) * 2.0; + let y = f64::from(y) * 2.0; + let mesh = Mesh { + positions: vec![ + Vec3::new(x, y, -0.01), + Vec3::new(x + 2.0, y, -0.01), + Vec3::new(x + 2.0, y + 2.0, -0.01), + Vec3::new(x, y + 2.0, -0.01), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + meshes.push(ProductMesh { + name: "original checker tile".into(), + mesh: Arc::new(mesh), + color: [200; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(color, 0.0, 0.65, 1.5).unwrap()), + transmission: None, + faces: vec![], + }); + } + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |a, m| a.union(&m.mesh.bounds())); + let camera = Camera { target: Vec3::new(0.0, 0.0, 1.0), yaw: -0.45, pitch: 0.5, distance: 13.0, fov: 0.65, ..Default::default() }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Default::default(), + raytrace: None, + textures: None, + environment: None, + camera, + width: 960, + height: 720, + background: [236, 240, 245], + transparent_background: false, + }; + let lens = + std::env::var_os("SOLIDCRAFT_GLASS_DOF").map(|_| solidcraft_render::job::ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 12.0 }); + let options = JobOptions { samples: 256, max_depth: 16, seed: 1948, lens, ..Default::default() }; + let mut task = Task::new(executor.context.clone(), ProductScene { meshes, bounds }, request, options, CancelToken::default()).unwrap(); + task.environment = 1.0; + loop { + if let TaskPoll::Complete(png) = task.step(4096).unwrap() { + std::fs::write(&output, png).unwrap(); + break; + } + } +} + +fn glass_slab(thin: bool) -> ProductScene { + let mut mesh = Mesh::default(); + let faces = [ + ([[-10., -10., 0.5], [10., -10., 0.5], [10., 10., 0.5], [-10., 10., 0.5]], Vec3::Z), + ([[-10., 10., -0.5], [10., 10., -0.5], [10., -10., -0.5], [-10., -10., -0.5]], -Vec3::Z), + ([[10., -10., -0.5], [10., 10., -0.5], [10., 10., 0.5], [10., -10., 0.5]], Vec3::X), + ([[-10., 10., -0.5], [-10., -10., -0.5], [-10., -10., 0.5], [-10., 10., 0.5]], -Vec3::X), + ([[10., 10., -0.5], [-10., 10., -0.5], [-10., 10., 0.5], [10., 10., 0.5]], Vec3::Y), + ([[-10., -10., -0.5], [10., -10., -0.5], [10., -10., 0.5], [-10., -10., 0.5]], -Vec3::Y), + ]; + for (index, (positions, normal)) in faces.into_iter().enumerate() { + if thin && index > 0 { + break; + } + let offset = mesh.positions.len() as u32; + for p in positions { + mesh.positions.push(Vec3::new(p[0], p[1], p[2])); + mesh.normals.push(normal); + } + mesh.triangles.extend([[offset, offset + 1, offset + 2], [offset, offset + 2, offset + 3]]); + mesh.tri_face.extend([0, 0]); + } + let bounds = mesh.bounds(); + ProductScene { + bounds, + meshes: vec![ProductMesh { + name: "original slab".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()), + transmission: Some( + solidcraft_render::transmission::Transmission::new(Vec3::new(-0.5_f64.ln(), -0.8_f64.ln(), 0.0), thin.then_some(1.0)).unwrap(), + ), + faces: vec![], + }], + } +} + +#[test] +fn gpu_solid_and_thin_slabs_match_absorbing_interreflection_oracle() { + let Some(executor) = executor() else { return }; + for (thin, thickness) in [(false, 1.0), (true, 1.0), (true, 0.0)] { + let mut scene = glass_slab(thin); + if thin { + let sigma = scene.meshes[0].transmission.unwrap().extinction(); + scene.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(sigma, Some(thickness)).unwrap()); + } + let (_, expected) = solidcraft_render::transmission::slab(scene.meshes[0].transmission.unwrap(), thickness, 1.0, 1.0, 1.5).unwrap(); + let mut request = request(1); + request.camera.fov = 0.0001; + let options = JobOptions { samples: 4096, max_depth: 16, seed: 1948, ..Default::default() }; + let mut task = Task::new(executor.context.clone(), scene, request, options, CancelToken::default()).unwrap(); + task.environment = 1.0; + task.environment_bottom_only = true; + // Deliberately large offset: Beer uses unshifted geometric endpoints. + task.epsilon = 0.05; + task.studio = 0.0; + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let actual = task.read_linear().unwrap()[0]; + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 0.015, "slab thin={thin} thickness={thickness}: {actual:?} vs {expected:?}"); + } + } +} + +#[test] +fn shader_validates_without_a_device() { + let module = naga::front::wgsl::parse_str(SHADER).unwrap(); + let parameters = module.types.iter().find(|(_, ty)| ty.name.as_deref() == Some("Params")).unwrap().1; + let naga::TypeInner::Struct { span, .. } = ¶meters.inner else { panic!("Params must be a struct") }; + assert_eq!(*span as usize, PARAMETER_BYTES); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap(); +} + +#[test] +fn render_lights_path_visibility_uniform_keeps_the_shader_contract() { + shader_validates_without_a_device(); + let request = request(4); + assert!(request.studio_weights.is_none()); +} + +/// #3217: the path tracer opens Vulkan adapters, or Metal on macOS, never D3D12 or GL. +#[test] +fn path_devices_are_vulkan_or_metal_only() { + let picked = crate::select::pick_path(crate::select::Policy::Auto, |_| true); + if let Some((adapter, _)) = &picked { + assert!(matches!(adapter.get_info().backend, wgpu::Backend::Vulkan | wgpu::Backend::Metal)); + } + if crate::select::path_backends().is_empty() { + assert!(picked.is_none()); + } +} + +#[test] +fn viewport_path_backends_keep_windows_on_its_selected_backend() { + for backend in [wgpu::Backend::Dx12, wgpu::Backend::Gl, wgpu::Backend::Vulkan] { + let allowed = viewport_path_backends(backend, true); + assert_eq!(allowed, wgpu::Backends::from(backend)); + assert_eq!(allowed.contains(wgpu::Backends::VULKAN), backend == wgpu::Backend::Vulkan); + } +} + +#[test] +fn viewport_path_backends_preserve_other_platforms() { + for backend in [wgpu::Backend::Vulkan, wgpu::Backend::Gl, wgpu::Backend::Metal] { + assert_eq!(viewport_path_backends(backend, false), crate::select::path_backends()); + } +} + +#[test] +fn admission_rejects_hostile_parameters_and_transparency() { + let mut scene = sphere(white()); + let mut r = request(16); + for size in [0, (GPU_PATH_LIMITS.max_dimension + 1) as u32, u32::MAX] { + r.width = size; + assert!(admission(&scene, &r, JobOptions::default()).is_err()); + } + r.width = 16; + for samples in [0, 4097, u32::MAX] { + assert!(admission(&scene, &r, JobOptions { samples, ..Default::default() }).is_err()); + } + for depth in [0, 17, u32::MAX] { + assert!(admission(&scene, &r, JobOptions { max_depth: depth, ..Default::default() }).is_err()); + } + for ev in [f64::NAN, f64::INFINITY, 33.0] { + assert!(admission(&scene, &r, JobOptions { exposure_ev: ev, ..Default::default() }).is_err()); + } + scene.meshes[0].opacity = 0.5; + assert!(admission(&scene, &r, JobOptions::default()).is_err()); + scene.meshes[0].opacity = 1.0; + Arc::make_mut(&mut scene.meshes[0].mesh).triangles[0][0] = u32::MAX; + assert!(scene::flatten(&scene, Vec3::ZERO, &CancelToken::default()).is_err()); +} + +#[test] +fn admission_applies_the_gpu_estimate_instead_of_the_cpu_raster_budget() { + // A library-bounded source (not an ordinary UI scene): about 100 MiB of face appearances + // on a small mesh at the largest image. Its CPU raster estimate is above 384 MiB (covered + // in the render crate); the GPU's own estimate stays within its 512 MiB job cap. + let count = (100 * 1024 * 1024 / std::mem::size_of::()).min(1_000_000); + let mut scene = sphere(white()); + let appearance = solidcraft_render::FaceAppearance { face: 0, color: [255; 3], opacity: 1.0, surface: None, transmission: None }; + scene.meshes[0].faces = vec![appearance; count]; + let r = request(2048); + let a = admission(&scene, &r, JobOptions::default()).unwrap(); + assert!(a.estimated_total_bytes <= 512 * 1024 * 1024, "{a:?}"); + assert_eq!(a.face_appearances, count as u64); + // The CPU host still rejects the same source. + assert_eq!(solidcraft_render::job::admit(&scene, &r).unwrap_err().code, ErrorCode::LimitExceeded); +} + +#[test] +fn bvh_handles_empty_and_cancelled_scenes() { + let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let upload = scene::flatten(&empty, Vec3::ZERO, &CancelToken::default()).unwrap(); + assert_eq!(upload.nodes.len(), 32); + assert_eq!(&upload.nodes[12..16], &u32::MAX.to_le_bytes()); + let cancel = CancelToken::default(); + cancel.cancel(); + assert_eq!(scene::flatten(&sphere(white()), Vec3::ZERO, &cancel).err().unwrap().code, ErrorCode::Cancelled); +} + +#[test] +fn gpu_brdf_matches_f64_surface_oracle() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("path BRDF reference"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("reference"), + compilation_options: Default::default(), + cache: None, + }); + for metallic in [0.0, 0.5, 1.0] { + for roughness in [0.045, 0.25, 1.0] { + for ior in [1.0, 1.5, 3.0] { + let surface = OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, roughness, ior).unwrap(); + let mut task = Task::new(context.clone(), sphere(surface), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + for (view, light) in [ + (Vec3::Z, Vec3::Z), + (Vec3::new(0.5, 0.2, 1.0), Vec3::new(-0.4, 0.3, 0.8)), + (Vec3::new(1.0, 0.0, 0.02), Vec3::new(-1.0, 0.1, 0.02)), + ] { + let view = view.normalized().unwrap(); + let light = light.normalized().unwrap(); + let mut params = vec![0; 48]; + scene::vector(&mut params, light, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + scene::vector(&mut params, view, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let expected = surface.brdf(Vec3::Z, view, light).unwrap(); + if metallic == 0.0 && ior == 1.0 { + let diffuse = Vec3::new(0.8, 0.5, 0.2) / std::f64::consts::PI; + assert!((expected - diffuse).len() < 1e-12, "index-matched diffuse has no interface reflection"); + } + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() <= 3e-3 * b.abs() + 2e-5, "m={metallic}, r={roughness}, ior={ior}: {a} vs {b}"); + } + } + } + } + } +} + +/// Assemble the same viewport declarations, lighting helpers and PBR implementation +/// as production, plus a compute entry point that calls the actual BRDF. +fn viewport_brdf_probe_source() -> String { + format!( + "{}\n{}\n{}", + crate::view::SHADER, + crate::pbr::SOURCE, + r#" +struct Probe { base: vec4, parameters: vec4, view: vec4, light: vec4, }; +// Bindings 0 and 1 belong to the production viewport uniform and palette. +@group(0) @binding(2) var probe: Probe; +@group(0) @binding(3) var result: array>; +@compute @workgroup_size(1) +fn probe_pbr() { + result[0] = vec4(pbr_brdf(probe.base.xyz, probe.parameters.xyz, + vec3(0.0,0.0,1.0),probe.view.xyz,probe.light.xyz),1.0); +} +"# + ) +} + +#[test] +fn viewport_brdf_probe_shader_is_valid() { + let source = viewport_brdf_probe_source(); + let module = naga::front::wgsl::parse_str(&source).unwrap_or_else(|error| panic!("{}", error.emit_to_string(&source))); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|error| panic!("{}", error.emit_to_string(&source))); +} + +/// The viewport embeds a separate WGSL translation. Exercise its actual function +/// on the same native device as the path-tracer oracle, not a copied Rust formula. +#[test] +fn viewport_brdf_matches_f64_surface_oracle_at_index_match() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let source = viewport_brdf_probe_source(); + let creation_scopes = scopes(&context.device); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("actual viewport PBR oracle"), + source: wgpu::ShaderSource::Wgsl(source.into()), + }); + let layout = context.device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + module: &shader, + entry_point: Some("probe_pbr"), + compilation_options: Default::default(), + cache: None, + }); + let uniform = context.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let values = context.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let readback = context.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 16, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = context.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { binding: 2, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: values.as_entire_binding() }, + ], + }); + checked(creation_scopes).expect("viewport BRDF probe resource creation must validate"); + for metallic in [0.0, 0.5, 1.0] { + for roughness in [0.045, 0.5, 1.0] { + for ior in [1.0, 1.5, 3.0] { + let base = Vec3::new(0.8, 0.5, 0.2); + let surface = OpaqueSurface::new(base, metallic, roughness, ior).unwrap(); + for (view, light) in [ + (Vec3::Z, Vec3::Z), + (Vec3::new(0.5, 0.0, 1.0).normalized().unwrap(), Vec3::new(-0.4, 0.3, 0.8).normalized().unwrap()), + (Vec3::new(1.0, 0.0, 0.02).normalized().unwrap(), Vec3::new(-1.0, 0.1, 0.02).normalized().unwrap()), + ] { + let input = [ + 0.8_f32, + 0.5, + 0.2, + 0.0, + metallic as f32, + roughness as f32, + ior as f32, + 0.0, + view.x as f32, + view.y as f32, + view.z as f32, + 0.0, + light.x as f32, + light.y as f32, + light.z as f32, + 0.0, + ]; + let bytes: Vec = input.iter().flat_map(|value| value.to_le_bytes()).collect(); + let dispatch_scopes = scopes(&context.device); + context.queue.write_buffer(&uniform, 0, &bytes); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + encoder.copy_buffer_to_buffer(&values, 0, &readback, 0, 16); + let submission = context.queue.submit([encoder.finish()]); + checked(dispatch_scopes).expect("viewport BRDF probe dispatch must validate"); + let slice = readback.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = tx.send(result); + }); + context.wait(submission, TIMEOUT).unwrap(); + rx.try_recv().unwrap().unwrap(); + let data = slice.get_mapped_range().unwrap(); + let actual: Vec = data.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes)).collect(); + drop(data); + readback.unmap(); + let expected = surface.brdf(Vec3::Z, view, light).unwrap(); + if metallic == 0.0 && ior == 1.0 { + assert!((expected - base / std::f64::consts::PI).len() < 1e-12); + } + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5 + 3e-3 * b.abs(), "viewport m={metallic}, r={roughness}, ior={ior}: {a} vs {b}"); + } + } + } + } + } +} + +#[test] +fn gpu_tiny_scene_matches_cpu_studio_with_face_appearance() { + let Some(executor) = executor() else { return }; + let surface = OpaqueSurface::new(Vec3::new(0.7, 0.2, 0.1), 0.5, 0.3, 1.5).unwrap(); + let mesh = Mesh { + positions: vec![Vec3::new(-3.0, -3.0, 0.0), Vec3::new(3.0, -3.0, 0.0), Vec3::new(3.0, 3.0, 0.0), Vec3::new(-3.0, 3.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![7, 9], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![ProductMesh { + name: "reference plane".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(white()), + transmission: None, + faces: [7, 9] + .map(|face| solidcraft_render::FaceAppearance { face, color: [0; 3], opacity: 1.0, surface: Some(surface), transmission: None }) + .to_vec(), + }], + bounds, + }; + let mut task = + Task::new(executor.context.clone(), scene, request(4), JobOptions { samples: 4, max_depth: 1, ..Default::default() }, CancelToken::default()) + .unwrap(); + for _ in 0..4 { + task.complete_sample().unwrap(); + } + let actual = task.read_linear().unwrap(); + let expected = solidcraft_render::studio::shade(surface, Vec3::Z, Vec3::Z).unwrap(); + for pixel in actual { + assert_eq!(pixel[3], 1.0); + for (a, b) in pixel.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 3e-3 * b.abs() + 2e-5, "{a} vs {b}"); + } + } +} + +#[test] +fn gpu_furnace_fixed_seed_and_cancellation() { + let Some(executor) = executor() else { return }; + let options = JobOptions { samples: 4096, max_depth: 8, seed: 37, ..Default::default() }; + let mut task = Task::new(executor.context.clone(), sphere(white()), request(8), options, CancelToken::default()).unwrap(); + task.environment = 1.0; + task.studio = 0.0; + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let result = task.read_linear().unwrap(); + eprintln!("furnace centre {:?}; BVH {:.3} ms; upload {} bytes / {:.3} ms", result[27], task.metrics.0, task.metrics.1, task.metrics.2); + // The oracle includes Schlick entry/exit attenuation even at IOR=1, plus single- + // scattering GGX. It is near-white, not an exactly energy-preserving Lambert model. + for index in [27, 28, 35, 36] { + assert!((result[index][0] - 1.0).abs() < 0.07, "furnace radiance: {:?}", result[index]); + } + let mut repeat = Task::new(executor.context.clone(), sphere(white()), request(8), options, CancelToken::default()).unwrap(); + repeat.environment = 1.0; + repeat.studio = 0.0; + for _ in 0..options.samples { + repeat.complete_sample().unwrap(); + } + assert_eq!(result, repeat.read_linear().unwrap(), "fixed sample indices and seed must repeat on the same adapter"); + let token = CancelToken::default(); + let mut cancelled = Task::new(executor.context.clone(), sphere(white()), request(16), options, token.clone()).unwrap(); + cancelled.dispatch().unwrap(); + token.cancel(); + assert_eq!(cancelled.step(4096).err().unwrap().code, ErrorCode::Cancelled); +} + +#[test] +fn skinny_polar_triangles_do_not_shadow_themselves() { + let Some(executor) = executor() else { return }; + let mut image = request(32); + image.camera.distance = 16.0; + image.camera.fov = 0.0005; + let mut task = Task::new( + executor.context.clone(), + sphere_section(white(), 512, 1024, 1), + image, + JobOptions { samples: 1, max_depth: 1, ..Default::default() }, + CancelToken::default(), + ) + .unwrap(); + task.complete_sample().unwrap(); + let pixels = task.read_linear().unwrap(); + for (index, pixel) in pixels.iter().enumerate() { + assert_eq!(pixel[3], 1.0, "polar cap covers the image: {index} {pixel:?}"); + assert!(pixel[0] > 0.1, "outward-facing cap must receive unobstructed studio light: {index} {pixel:?}"); + } +} + +#[test] +fn native_host_cancel_never_publishes_a_frame() { + let Some(executor) = executor() else { return }; + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + let job = host + .submit_with_options( + solidcraft_render::job::JobId { session: 1, serial: 1, generation: 1 }, + 1, + sphere(white()), + request(64), + JobOptions { samples: 4096, ..Default::default() }, + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + let status = job.status().unwrap(); + if status.progress.phase == Phase::Running { + break; + } + assert!(!status.progress.phase.terminal(), "{status:?}"); + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + } + job.cancel().unwrap(); + assert_eq!(job.wait_timeout(Duration::from_secs(30)).unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); +} + +/// Explicit benchmark: large allocation and sustained GPU load must not run in ordinary CI. +#[test] +#[ignore = "manual 1M-triangle 1920x1080 GPU performance measurement"] +fn path_performance() { + let executor = executor().expect("benchmark requires an adapter"); + let samples = std::env::var("SOLIDCRAFT_PATH_BENCH_SAMPLES").ok().map(|s| s.parse::().unwrap()).unwrap_or(1); + let options = JobOptions { samples, ..Default::default() }; + options.validate().unwrap(); + let surface = OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 0.25, 0.4, 1.5).unwrap(); + let scene = sphere_grid(surface, 512, 1024); + let mut request = request(1920); + request.height = 1080; + let admitted = executor.admit(&scene, &request, options).unwrap(); + let mut task = Task::new(executor.context.clone(), scene, request, options, CancelToken::default()).unwrap(); + let started = Instant::now(); + while task.sample < samples { + task.complete_sample().unwrap(); + } + let seconds = started.elapsed().as_secs_f64(); + let linear = task.read_linear().unwrap(); + assert!(linear.iter().all(|p| p.iter().all(|v| v.is_finite()))); + let coverage = linear.iter().map(|p| f64::from(p[3])).sum::() / linear.len() as f64; + assert!((0.16..0.19).contains(&coverage), "sphere must occupy the expected projected area: {coverage}"); + let centre = linear[540 * 1920 + 960]; + let lit = linear.iter().filter(|p| p[0] > 0.01).count(); + eprintln!( + "PATH_BENCH_DIAGNOSTIC coverage={coverage:.6} centre={centre:?} lit_pixels={lit} nearby={:?}", + [linear[500 * 1920 + 960], linear[540 * 1920 + 1000], linear[580 * 1920 + 960]] + ); + assert_eq!(centre[3], 1.0); + assert!(centre[0] > 0.01, "benchmark must actually shade the sphere: {centre:?}"); + eprintln!("PATH_BENCH_IMAGE coverage={coverage:.6} centre={centre:?}"); + eprintln!( + "PATH_BENCH input_triangles={} resolution=1920x1080 spp={} bvh_ms={:.3} upload_bytes={} upload_ms={:.3} admitted_bytes={} render_seconds={:.6} ms_per_spp={:.3}", + admitted.triangles, + samples, + task.metrics.0, + task.metrics.1, + task.metrics.2, + admitted.estimated_total_bytes, + seconds, + seconds * 1000.0 / f64::from(samples) + ); +} + +#[test] +fn admission_refuses_cpu_options_without_opening_a_device() { + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let mut input = request(16); + input.integrator = solidcraft_render::job::Integrator::Raytrace; + assert_eq!(admission(&scene, &input, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + input.integrator = solidcraft_render::job::Integrator::Raster; + input.raytrace = Some(solidcraft_render::job::RaytraceOptions::default()); + assert_eq!(admission(&scene, &input, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); +} + +#[test] +fn gpu_clear_coat_brdf_matches_f64_surface_oracle() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("path BRDF reference"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("reference"), + compilation_options: Default::default(), + cache: None, + }); + for metallic in [0.0, 1.0] { + for roughness in [0.045, 0.12, 0.5] { + for ior in [1.5, 3.0] { + let surface = OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, 0.3, 1.5) + .unwrap() + .with_clear_coat(solidcraft_render::clear_coat::ClearCoat::new(1.0, roughness, ior).unwrap()); + let mut task = Task::new(context.clone(), sphere(surface), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + for (view, light) in [ + (Vec3::Z, Vec3::Z), + (Vec3::new(0.5, 0.2, 1.0), Vec3::new(-0.4, 0.3, 0.8)), + (Vec3::new(1.0, 0.0, 0.02), Vec3::new(-1.0, 0.1, 0.02)), + ] { + let view = view.normalized().unwrap(); + let light = light.normalized().unwrap(); + let mut params = vec![0; 48]; + scene::vector(&mut params, light, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + scene::vector(&mut params, view, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let expected = surface.brdf(Vec3::Z, view, light).unwrap(); + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() <= 3e-3 * b.abs() + 2e-5, "m={metallic}, r={roughness}, ior={ior}: {a} vs {b}"); + } + } + } + } + } +} + +#[test] +fn gpu_clear_coat_pdf_matches_f64_surface_oracle() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("path BRDF reference"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("pdf_reference"), + compilation_options: Default::default(), + cache: None, + }); + for metallic in [0.0, 1.0] { + for roughness in [0.045, 0.12, 0.5] { + for ior in [1.5, 3.0] { + let surface = OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.2), metallic, 0.3, 1.5) + .unwrap() + .with_clear_coat(solidcraft_render::clear_coat::ClearCoat::new(1.0, roughness, ior).unwrap()); + let mut task = Task::new(context.clone(), sphere(surface), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + for (view, light) in [ + (Vec3::Z, Vec3::Z), + (Vec3::new(0.5, 0.2, 1.0), Vec3::new(-0.4, 0.3, 0.8)), + (Vec3::new(1.0, 0.0, 0.02), Vec3::new(-1.0, 0.1, 0.02)), + ] { + let view = view.normalized().unwrap(); + let light = light.normalized().unwrap(); + let mut params = vec![0; 48]; + scene::vector(&mut params, light, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + scene::vector(&mut params, view, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let expected = solidcraft_render::clear_coat::surface_pdf(surface, Vec3::Z, view, light).unwrap(); + for (a, b) in actual.iter().zip([expected, 0.0, 0.0]) { + assert!((f64::from(*a) - b).abs() <= 3e-3 * b.abs() + 2e-5, "m={metallic}, r={roughness}, ior={ior}: {a} vs {b}"); + } + } + } + } + } +} + +#[test] +fn gpu_clear_coat_samples_the_pdf_mixture_components() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("coat sampling oracle"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("surface_sample_reference"), + compilation_options: Default::default(), + cache: None, + }); + for weight in [0.0, 0.4, 1.0] { + let surface = OpaqueSurface::new(Vec3::new(0.02, 0.02, 0.02), 0.0, 0.45, 1.5) + .unwrap() + .with_clear_coat(solidcraft_render::clear_coat::ClearCoat::new(weight, 0.12, 1.5).unwrap()); + let mut task = Task::new(context.clone(), sphere(surface), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + let p = weight * 0.5; + // One variate strictly inside each nonempty mixture interval. + for component in [(1.0 - p) * 0.25, (1.0 - p) * 0.75, 1.0 - p * 0.5] { + if component >= 1.0 { + continue; + } + for x in [0.125_f64, 0.75] { + let mut params = vec![0; 48]; + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + scene::vector(&mut params, Vec3::new(component, x, 0.25), 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let expected = if component < (1.0 - p) * 0.5 { + Vec3::new(0.0, x.sqrt(), (1.0 - x).sqrt()) + } else { + let r = if component >= 1.0 - p { 0.12_f64 } else { 0.45_f64 }; + let c = ((1.0 - x) / (1.0 + (r.powi(4) - 1.0) * x)).sqrt(); + Vec3::new(0.0, 2.0 * c * (1.0 - c * c).sqrt(), 2.0 * c * c - 1.0) + } + Vec3::new(2.0, 2.0, 2.0); + for (a, b) in actual.iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5, "weight={weight}, component={component}, x={x}: {actual:?}, {expected:?}"); + } + } + } + } +} + +#[test] +fn gpu_studio_area_mis_matches_independent_quadrature_and_distance_visibility() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let surface = white(); + let plane = |z: f64| { + let mesh = Mesh { + positions: vec![Vec3::new(-10.0, -10.0, z), Vec3::new(10.0, -10.0, z), Vec3::new(10.0, 10.0, z), Vec3::new(-10.0, 10.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + ProductMesh { + name: "original quadrature plane".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(surface), + transmission: None, + faces: Vec::new(), + } + }; + let light = AreaLight { center: [2.0, 0.0, 2.0], u: [1.0, 0.0, 0.0], v: [0.0, -1.0, 0.0], radiance: [3.0; 3] }; + let mut expected = 0.0; + for y in 0..256 { + for x in 0..256 { + let delta = Vec3::new(1.0 + (f64::from(x) + 0.5) / 128.0, -1.0 + (f64::from(y) + 0.5) / 128.0, 2.0); + let l = delta.normalized().unwrap(); + expected += surface.brdf(Vec3::Z, Vec3::Z, l).unwrap().x * 3.0 * l.z * l.z / delta.len2() * 4.0 / (256.0 * 256.0); + } + } + for depth in [1, 2] { + for blocker in [None, Some(4.0), Some(1.0)] { + let mut scene = ProductScene { meshes: vec![plane(0.0)], bounds: Aabb3::EMPTY }; + if let Some(z) = blocker { + scene.meshes.push(plane(z)); + } + // Camera sits below any blocker and sees the receiver. Geometry behind + // the emitter must not shadow it; the nearer blocker must. + let mut image = request(1); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + let options = JobOptions { + samples: 4096, + max_depth: depth, + seed: 37, + lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); + assert_eq!(task.parameters(1).len(), PARAMETER_BYTES); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let value = f64::from(task.read_linear().unwrap()[0][0]); + if blocker == Some(1.0) { + assert!(value < 1e-6, "blocked depth{depth}: {value}"); + } else { + assert!((value - expected).abs() < 0.04 * expected, "depth{depth}, blocker{blocker:?}: {value} vs {expected}"); + } + } + } +} + +#[test] +fn gpu_studio_environment_mis_matches_furnace_at_last_and_continuing_bounces() { + use solidcraft_render::job::StudioLighting; + let Some(executor) = executor() else { return }; + for depth in [1, 2] { + let options = JobOptions { + samples: 4096, + max_depth: depth, + seed: 37, + lighting: Some(StudioLighting { sun: None, environment: [1.0; 3], ..Default::default() }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), sphere(white()), request(8), options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let pixels = task.read_linear().unwrap(); + for index in [27, 28, 35, 36] { + assert!((pixels[index][0] - 1.0).abs() < 0.07, "depth{depth}: {:?}", pixels[index]); + } + } +} + +#[test] +fn gpu_emitter_inside_glass_applies_final_segment_absorption() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let mut glass = sphere(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.0).unwrap()); + glass.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::new(0.7, 0.3, 0.0), None).unwrap()); + let light = AreaLight { center: [0.0; 3], u: [0.4, 0.0, 0.0], v: [0.0, 0.4, 0.0], radiance: [3.0; 3] }; + let options = JobOptions { + samples: 16, + max_depth: 2, + lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + ..Default::default() + }; + let mut image = request(2); + image.camera.fov = 0.0001; + let mut task = Task::new(executor.context.clone(), glass, image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + for pixel in task.read_linear().unwrap() { + for (value, sigma) in pixel.iter().zip([0.7_f64, 0.3, 0.0]) { + assert!((f64::from(*value) - 3.0 * (-sigma).exp()).abs() < 0.002, "{pixel:?}"); + } + } +} + +fn environment_plane() -> ProductScene { + let mesh = Mesh { + positions: vec![Vec3::new(-3.0, -3.0, 0.0), Vec3::new(3.0, -3.0, 0.0), Vec3::new(3.0, 3.0, 0.0), Vec3::new(-3.0, 3.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + let bounds = mesh.bounds(); + ProductScene { + meshes: vec![ProductMesh { + name: "original environment test plane".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(white()), + transmission: None, + faces: Vec::new(), + }], + bounds, + } +} +fn original_hdr() -> Vec { + 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, 128, 128, 129]); + } + bytes +} +#[test] +fn gpu_hdr_environment_matches_constant_furnace_and_resource_admission() { + use solidcraft_render::lighting::environment::EnvironmentSource; + let Some(executor) = executor() else { return }; + let source = Arc::new(EnvironmentSource::hdr(original_hdr(), 0.3, 1.0, false).unwrap()); + let mut image = request(8); + image.environment = Some(source.clone()); + let options = JobOptions { samples: 2048, max_depth: 2, seed: 37, ..Default::default() }; + let plain = admission(&sphere(white()), &request(8), options).unwrap(); + let with_map = admission(&sphere(white()), &image, options).unwrap(); + assert_eq!(with_map.estimated_total_bytes - plain.estimated_total_bytes, source.admitted_bytes()); + let mut task = Task::new(executor.context.clone(), sphere(white()), image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let pixels = task.read_linear().unwrap(); + for index in [27, 28, 35, 36] { + assert!((pixels[index][0] - 1.0).abs() < 0.07, "{:?}", pixels[index]); + } +} +#[test] +fn gpu_finite_sun_matches_cone_quadrature_at_final_and_continuing_bounces() { + use solidcraft_render::job::{StudioLighting, Sun}; + let Some(executor) = executor() else { return }; + let sun = Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.4, radiance: [3.0; 3] }; + let mut expected = 0.0; + for i in 0..4096 { + let z = 1.0 - (f64::from(i) + 0.5) / 4096.0 * (1.0 - sun.angular_radius_rad.cos()); + let l = Vec3::new((1.0 - z * z).sqrt(), 0.0, z); + expected += white().brdf(Vec3::Z, Vec3::Z, l).unwrap().x * z * 3.0 * sun.solid_angle() / 4096.0; + } + for max_depth in [1, 2] { + let mut image = request(2); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + let options = JobOptions { + samples: 2048, + max_depth, + seed: 123, + lighting: Some(StudioLighting { sun: Some(sun), ..Default::default() }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), environment_plane(), image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + for pixel in task.read_linear().unwrap() { + assert!((f64::from(pixel[0]) - expected).abs() < 0.03 * expected, "depth{max_depth}: {pixel:?}, {expected}"); + } + } +} + +#[test] +fn gpu_environment_orientation_rotation_intensity_and_pdf_match_cpu() { + use solidcraft_render::lighting::environment::EnvironmentSource; + let Some(executor) = executor() else { return }; + let context = &executor.context; + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 2 +X 4\n".to_vec(); + for i in 0..8u8 { + bytes.extend_from_slice(&[16 * (i + 1), 32, 64, 129]); + } + let rotation = 0.7_f64; + let intensity = 2.5; + let source = Arc::new(EnvironmentSource::hdr(bytes, rotation, intensity, true).unwrap()); + let cpu = source.prepare(&CancelToken::default()).unwrap(); + let mut image = request(1); + image.environment = Some(source); + let mut task = Task::new(context.clone(), sphere(white()), image, JobOptions::default(), CancelToken::default()).unwrap(); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("environment_reference"), + compilation_options: Default::default(), + cache: None, + }); + for row in 0..2 { + for column in 0..4 { + let theta = std::f64::consts::PI * (f64::from(row) + 0.5) / 2.0; + let phi = std::f64::consts::TAU * (f64::from(column) + 0.5) / 4.0; + let local = Vec3::new(theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos()); + let direction = + Vec3::new(rotation.cos() * local.x - rotation.sin() * local.y, rotation.sin() * local.x + rotation.cos() * local.y, local.z); + let mut params = task.parameters(1); + for (out, value) in params[48..60].as_chunks_mut::<4>().0.iter_mut().zip([direction.x, direction.y, direction.z]) { + out.copy_from_slice(&(value as f32).to_le_bytes()); + } + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap()[0]; + let (rgb, pdf) = cpu.evaluate(local).unwrap(); + for (a, b) in actual.iter().zip(rgb.into_iter().map(|v| v * intensity as f32).chain([pdf])) { + assert!((a - b).abs() < 1e-5, "{actual:?} vs {rgb:?}/{pdf}"); + } + } + } +} + +fn shadow_probe(context: &Arc, scene: ProductScene, origin: Vec3, direction: Vec3, limit: f64) -> [[f32; 4]; 2] { + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("shadow connection oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("shadow_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, origin, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, direction, limit as f32); + // Large offset catches Beer intervals incorrectly measured from shifted origins. + scene::vector(&mut params, Vec3::new(0.01, 0.0, 0.0), 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let pixels = task.read_linear().unwrap(); + [pixels[0], pixels[1]] +} + +#[test] +fn gpu_shadow_sheets_solids_endpoints_and_invalid_crossings_match_oracles() { + use solidcraft_render::transmission::{slab, solid_shadow}; + let Some(executor) = executor() else { return }; + let context = &executor.context; + for thin in [true, false] { + let mut scene = glass_slab(thin); + let optics = scene.meshes[0].transmission.unwrap().with_shadow_transmission(true); + scene.meshes[0].transmission = Some(optics); + for cosine in [1.0_f64, 0.8] { + let d = Vec3::new((1.0 - cosine * cosine).sqrt(), 0.0, -cosine); + let actual = shadow_probe(context, scene.clone(), Vec3::new(0.0, 0.0, 2.0), d, 8.0); + let expected = + if thin { slab(optics, 1.0, cosine, 1.0, 1.5).unwrap().1 } else { solid_shadow(optics, 1.0 / cosine, cosine, cosine, 1.5).unwrap() }; + for (a, b) in actual[0].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5, "thin={thin}, cosine={cosine}: {actual:?} vs {expected:?}"); + } + assert_eq!(actual[1][1], if thin { 1.0 } else { 2.0 }); + } + let before = shadow_probe(context, scene.clone(), Vec3::new(0.0, 0.0, 2.0), -Vec3::Z, 1.0); + assert_eq!(before[0], [1.0; 4]); + if !thin { + let inside = shadow_probe(context, scene.clone(), Vec3::new(0.0, 0.0, 2.0), -Vec3::Z, 2.0); + let expected = optics.attenuation(0.5).unwrap() * (0.96 / 2.25); + for (a, b) in inside[0].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5); + } + // Shadow rays start at shading points, which may touch or lie inside + // glass. A first exit infers that medium and absorbs from the origin. + let from_inside = shadow_probe(context, scene.clone(), Vec3::ZERO, Vec3::Z, 8.0); + let expected = optics.attenuation(0.5).unwrap() * 0.96; + for (a, b) in from_inside[0].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5, "{from_inside:?} vs {expected:?}"); + } + assert_eq!(from_inside[1][1], 1.0); + } + scene.meshes[0].transmission = Some(optics.with_shadow_transmission(false)); + assert_eq!(shadow_probe(context, scene, Vec3::new(0.0, 0.0, 2.0), -Vec3::Z, 8.0)[0], [0.0, 0.0, 0.0, 1.0]); + } + let mut opaque = glass_slab(true); + opaque.meshes[0].transmission = None; + assert_eq!(shadow_probe(context, opaque, Vec3::new(0.0, 0.0, 2.0), -Vec3::Z, 8.0)[0], [0.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn gpu_shadow_interface_walk_is_bounded_and_stacked_sheet_pdf_matches() { + let Some(executor) = executor() else { return }; + for count in [2_u32, 64, 65] { + let mut scene = glass_slab(true); + let base = scene.meshes[0].mesh.clone(); + let mut mesh = Mesh::default(); + for layer in 0..count { + let offset = mesh.positions.len() as u32; + mesh.positions.extend(base.positions.iter().map(|p| *p - Vec3::Z * f64::from(layer))); + mesh.normals.extend_from_slice(&base.normals); + mesh.triangles.extend(base.triangles.iter().map(|t| t.map(|i| i + offset))); + mesh.tri_face.extend_from_slice(&base.tri_face); + } + scene.meshes[0].mesh = Arc::new(mesh); + scene.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, Some(0.0)).unwrap()); + let actual = shadow_probe(&executor.context, scene, Vec3::new(0.0, 0.0, 2.0), -Vec3::Z, 100.0); + if count == 65 { + assert_eq!(actual[0], [0.0, 0.0, 0.0, 1.0]); + } else { + let expected = (0.96_f64 / 1.04).powi(count as i32); + assert!((f64::from(actual[0][0]) - expected).abs() < 2e-5); + assert!((f64::from(actual[1][0]) - expected).abs() < 2e-5); + assert_eq!(actual[1][1], count as f32); + } + } +} + +#[test] +fn gpu_shadow_mis_does_not_double_direct_energy_through_index_matched_glass() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let surface = white(); + let receiver = ProductMesh { + name: "shadow MIS receiver".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, -2.0), Vec3::new(20.0, -20.0, -2.0), Vec3::new(20.0, 20.0, -2.0), Vec3::new(-20.0, 20.0, -2.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(surface), + transmission: None, + faces: vec![], + }; + let light = AreaLight { center: [0.0, 0.0, 2.0], u: [4.0, 0.0, 0.0], v: [0.0, -4.0, 0.0], radiance: [1.0; 3] }; + let mut expected = 0.0; + for y in 0..128 { + for x in 0..128 { + let delta = Vec3::new(-4.0 + (f64::from(x) + 0.5) / 16.0, -4.0 + (f64::from(y) + 0.5) / 16.0, 4.0); + let l = delta.normalized().unwrap(); + expected += surface.brdf(Vec3::Z, Vec3::Z, l).unwrap().x * l.z * l.z / delta.len2() * 64.0 / 16384.0; + } + } + for (thin, enabled, depth) in [(true, true, 2), (true, true, 4), (true, false, 4), (false, true, 1), (false, true, 4), (false, false, 4)] { + let mut scene = glass_slab(thin); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.0).unwrap()); + scene.meshes[0].transmission = + Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, thin.then_some(0.0)).unwrap().with_shadow_transmission(enabled)); + scene.meshes.push(receiver.clone()); + let options = JobOptions { + samples: 4096, + max_depth: depth, + seed: 37, + lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + ..Default::default() + }; + let mut image = request(1); + image.camera.target = Vec3::new(0.0, 0.0, -2.0); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let actual = f64::from(task.read_linear().unwrap()[0][0]); + assert!((actual - expected).abs() < 0.08 * expected, "thin={thin}, enabled={enabled}, depth={depth}: {actual} vs {expected}"); + } +} + +#[test] +fn gpu_absorbing_two_sheet_mis_matches_f64_quadrature() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let surface = white(); + // A tiny receiver excludes sheet-reflection returns from this direct-only oracle. + // Its half-width still exceeds the primary ray footprint by two orders of magnitude. + let receiver = ProductMesh { + name: "shadow MIS receiver".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-0.01, -0.01, -2.0), Vec3::new(0.01, -0.01, -2.0), Vec3::new(0.01, 0.01, -2.0), Vec3::new(-0.01, 0.01, -2.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(surface), + transmission: None, + faces: vec![], + }; + let light = AreaLight { center: [0.0, 0.0, 2.0], u: [4.0, 0.0, 0.0], v: [0.0, -4.0, 0.0], radiance: [1.0; 3] }; + let optics = solidcraft_render::transmission::Transmission::new(Vec3::new(0.2, 0.1, 0.05), Some(0.7)).unwrap(); + let mut expected = 0.0; + for y in 0..128 { + for x in 0..128 { + let delta = Vec3::new(-4.0 + (f64::from(x) + 0.5) / 16.0, -4.0 + (f64::from(y) + 0.5) / 16.0, 4.0); + let l = delta.normalized().unwrap(); + let transmission = solidcraft_render::transmission::slab(optics, 0.7, l.z, 1.0, 1.5).unwrap().1.x; + expected += transmission * transmission * surface.brdf(Vec3::Z, Vec3::Z, l).unwrap().x * l.z * l.z / delta.len2() * 64.0 / 16384.0; + } + } + for (thin, enabled, depth) in [(true, true, 1), (true, true, 4), (true, false, 4)] { + let mut scene = glass_slab(thin); + scene.meshes[0].transmission = Some(optics.with_shadow_transmission(enabled)); + let mut second = scene.meshes[0].clone(); + second.name = "second absorbing sheet".into(); + for p in &mut Arc::make_mut(&mut second.mesh).positions { + p.z -= 1.0; + } + scene.meshes.push(second); + scene.meshes.push(receiver.clone()); + let options = JobOptions { + samples: 4096, + max_depth: depth, + seed: 37, + lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + ..Default::default() + }; + let mut image = request(1); + image.camera.target = Vec3::new(0.0, 0.0, -2.0); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let actual = f64::from(task.read_linear().unwrap()[0][0]); + assert!((actual - expected).abs() < 0.08 * expected, "thin={thin}, enabled={enabled}, depth={depth}: {actual} vs {expected}"); + } +} + +#[test] +fn gpu_hdr_and_sun_shadow_mis_preserve_index_matched_energy() { + use solidcraft_render::job::{StudioLighting, Sun}; + use solidcraft_render::lighting::environment::EnvironmentSource; + let Some(executor) = executor() else { return }; + let sun = Sun { direction: [0.0, 0.0, 1.0], angular_radius_rad: 0.4, radiance: [3.0; 3] }; + let mut sun_expected = 0.0; + for i in 0..4096 { + let z = 1.0 - (f64::from(i) + 0.5) / 4096.0 * (1.0 - sun.angular_radius_rad.cos()); + let l = Vec3::new((1.0 - z * z).sqrt(), 0.0, z); + sun_expected += white().brdf(Vec3::Z, Vec3::Z, l).unwrap().x * z * 3.0 * sun.solid_angle() / 4096.0; + } + // The original HDR has unit radiance everywhere. With IOR one the receiver + // is pure diffuse; retain the independent directional-albedo quadrature. + let mut hdr_expected = 0.0; + for i in 0..256 { + let z = (f64::from(i) + 0.5) / 256.0; + for j in 0..256 { + let phi = (f64::from(j) + 0.5) / 256.0 * std::f64::consts::TAU; + let l = Vec3::new((1.0 - z * z).sqrt() * phi.cos(), (1.0 - z * z).sqrt() * phi.sin(), z); + hdr_expected += white().brdf(Vec3::Z, Vec3::Z, l).unwrap().x * z * std::f64::consts::TAU / 65536.0; + } + } + for solar in [false, true] { + for (thin, depth) in [(true, 2), (true, 4), (false, 1), (false, 4)] { + let mut scene = glass_slab(thin); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.0).unwrap()); + scene.meshes[0].transmission = + Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, thin.then_some(0.0)).unwrap().with_shadow_transmission(true)); + let mut receiver = environment_plane().meshes.remove(0); + for p in &mut Arc::make_mut(&mut receiver.mesh).positions { + p.z -= 2.0; + } + scene.meshes.push(receiver); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, m| a.union(&m.mesh.bounds())); + let mut image = request(1); + image.camera.target = Vec3::new(0.0, 0.0, -2.0); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + if !solar { + image.environment = Some(Arc::new(EnvironmentSource::hdr(original_hdr(), 0.3, 1.0, false).unwrap())); + } + let options = JobOptions { + samples: 4096, + max_depth: depth, + seed: 37, + lighting: Some(StudioLighting { sun: solar.then_some(sun), ..Default::default() }), + ..Default::default() + }; + let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let actual = f64::from(task.read_linear().unwrap()[0][0]); + let expected = if solar { sun_expected } else { hdr_expected }; + assert!((actual - expected).abs() < 0.07 * expected, "sun={solar}, thin={thin}, depth={depth}: {actual} vs {expected}"); + } + } +} + +fn texture_fixture(frame: solidcraft_render::job::textures::PlanarFrame) -> Arc { + use image::ImageEncoder; + use solidcraft_render::{ + job::textures::{RuntimeTextures, TextureBinding, TextureMap}, + texture_input::MapRole, + }; + let map = |pixels: &[u8], role| { + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image(pixels, 2, 2, image::ExtendedColorType::Rgba8).unwrap(); + TextureMap::new(bytes, role).unwrap() + }; + Arc::new( + RuntimeTextures::new(vec![TextureBinding { + body_index: 0, + body_name: "original sphere".into(), + frame, + normal_strength: 0.75, + base_color: Some(map(&[128, 64, 255, 0, 255, 0, 32, 255, 64, 128, 192, 0, 0, 255, 128, 255], MapRole::BaseColor)), + normal: Some(map(&[128, 128, 255, 0, 192, 128, 224, 255, 128, 192, 224, 0, 64, 96, 224, 255], MapRole::NormalOpenGl)), + roughness: None, + metallic: None, + base_color_mode: Default::default(), + flip_v: false, + }]) + .unwrap(), + ) +} +#[test] +fn texture_admission_rejects_glass_and_stale_identity_and_honors_cancellation() { + use solidcraft_render::job::textures::PlanarFrame; + let source = texture_fixture(PlanarFrame { origin: [0.; 3], u: [1., 0., 0.], v: [0., 1., 0.] }); + let mut input = request(2); + input.textures = Some(source.clone()); + let mut scene = sphere(white()); + let plain = admission(&scene, &request(2), JobOptions::default()).unwrap(); + let textured = admission(&scene, &input, JobOptions::default()).unwrap(); + assert_eq!(textured.preparation_bytes - plain.preparation_bytes, source.working_bytes()); + assert!(solidcraft_render::job::admit(&scene, &input).is_err()); + let cancel = CancelToken::default(); + cancel.cancel(); + assert_eq!(textures::flatten(Some(&source), 1, Vec3::ZERO, &cancel).unwrap_err().code, ErrorCode::Cancelled); + scene.meshes[0].name = "stale".into(); + assert!(admission(&scene, &input, JobOptions::default()).is_err()); + scene.meshes[0].name = "original sphere".into(); + scene.meshes[0].transmission = Some(clear_glass()); + assert!(admission(&scene, &input, JobOptions::default()).is_err()); +} +#[test] +fn gpu_planar_color_and_normal_maps_match_cpu_sampling_oracle() { + use solidcraft_render::job::textures::{PlanarFrame, sample_map}; + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("texture_reference"), + compilation_options: Default::default(), + cache: None, + }); + for handed in [1., -1.] { + let frame = PlanarFrame { origin: [0.; 3], u: [2., 0., 0.], v: [0., 2. * handed, 0.] }; + let source = texture_fixture(frame); + let binding = &source.bindings()[0]; + let base = binding.base_color.as_ref().unwrap().decode(&CancelToken::default()).unwrap(); + let normals = binding.normal.as_ref().unwrap().decode(&CancelToken::default()).unwrap(); + for point in [Vec3::new(0.5, 0.5, 0.), Vec3::new(-0.25, 1.125, 0.), Vec3::new(0., 0., 0.)] { + let mut input = request(2); + input.textures = Some(source.clone()); + let mut task = Task::new(context.clone(), sphere(white()), input, JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, point, 0.); + scene::vector(&mut params, Vec3::ZERO, 0.); + scene::vector(&mut params, Vec3::Z, 0.); + scene::vector(&mut params, Vec3::Z, 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap(); + let uv = frame.uv(point).unwrap(); + let expected = sample_map(&base, [2, 2], uv).unwrap(); + let mapped = frame.mapped_normal(Vec3::Z, Vec3::Z, sample_map(&normals, [2, 2], uv).unwrap(), 0.75).unwrap(); + for (a, b) in actual[0].iter().zip(expected) { + assert!((f64::from(*a) - b).abs() < 2e-6, "color {actual:?} vs {expected:?}"); + } + for (a, b) in actual[1].iter().zip([mapped.x + 2., mapped.y + 2., mapped.z + 2.]) { + assert!((f64::from(*a) - b).abs() < 3e-6, "normal {actual:?} vs {mapped:?}"); + } + } + } +} + +#[test] +fn gpu_finite_emitter_inside_solid_retains_entry_radiance_eta() { + use solidcraft_render::job::{AreaLight, AreaLights, StudioLighting}; + let Some(executor) = executor() else { return }; + let surface = white(); + let receiver = ProductMesh { + name: "shadow MIS receiver".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-0.01, -0.01, -2.0), Vec3::new(0.01, -0.01, -2.0), Vec3::new(0.01, 0.01, -2.0), Vec3::new(-0.01, 0.01, -2.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(surface), + transmission: None, + faces: vec![], + }; + let light = AreaLight { center: [0.0, 0.0, 0.0], u: [9.0, 0.0, 0.0], v: [0.0, -9.0, 0.0], radiance: [1.0; 3] }; + // Broad finite emitter makes edge/refraction disagreement small; the missing eta term is a 125% error. + let mut expected = 0.0; + for y in 0..128 { + for x in 0..128 { + let delta = Vec3::new(-9.0 + (f64::from(x) + 0.5) * 18.0 / 128.0, -9.0 + (f64::from(y) + 0.5) * 18.0 / 128.0, 2.0); + let l = delta.normalized().unwrap(); + let r = solidcraft_render::transmission::fresnel(l.z, 1.0, 1.5).unwrap().reflectance(); + expected += (1.0 - r) / 2.25 * surface.brdf(Vec3::Z, Vec3::Z, l).unwrap().x * l.z * l.z / delta.len2() * 324.0 / 16384.0; + } + } + for (thin, enabled, depth) in [(false, true, 1), (false, true, 4), (false, false, 4)] { + let mut scene = glass_slab(thin); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap()); + scene.meshes[0].transmission = + Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, thin.then_some(0.0)).unwrap().with_shadow_transmission(enabled)); + scene.meshes.push(receiver.clone()); + let options = JobOptions { + samples: 4096, + max_depth: depth, + seed: 37, + lighting: Some(StudioLighting { sun: None, environment: [0.0; 3], area_lights: AreaLights::new(&[light]).unwrap() }), + ..Default::default() + }; + let mut image = request(1); + image.camera.target = Vec3::new(0.0, 0.0, -2.0); + image.camera.distance = 0.1; + image.camera.fov = 0.001; + let mut task = Task::new(executor.context.clone(), scene, image, options, CancelToken::default()).unwrap(); + for _ in 0..options.samples { + task.complete_sample().unwrap(); + } + let actual = f64::from(task.read_linear().unwrap()[0][0]); + assert!((actual - expected).abs() < 0.08 * expected, "thin={thin}, enabled={enabled}, depth={depth}: {actual} vs {expected}"); + } +} + +#[test] +fn path_device_limits_require_six_storage_buffers_without_changing_raster_defaults() { + let mut supported = wgpu::Limits::downlevel_defaults(); + assert_eq!(supported.max_storage_buffers_per_shader_stage, 4); + assert!(device_limits(supported.clone()).is_err()); + supported.max_storage_buffers_per_shader_stage = 8; + let requested = device_limits(supported.clone()).unwrap(); + let mut expected = wgpu::Limits::downlevel_defaults().using_resolution(supported); + expected.max_storage_buffers_per_shader_stage = 6; + assert_eq!(requested, expected); +} + +#[test] +fn gpu_secondary_closed_corner_exits_are_not_skipped() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("closed corner boundary oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("boundary_reference"), + compilation_options: Default::default(), + cache: None, + }); + for case in 0..3 { + let pyramid = case == 1; + let mut scene = glass_slab(false); + let (origin, direction) = if pyramid { + let mut mesh = Mesh::default(); + let corners = [Vec3::new(-1., -1., 1.), Vec3::new(1., -1., 1.), Vec3::new(1., 1., 1.), Vec3::new(-1., 1., 1.)]; + let tip = Vec3::new(0., 0., -1.); + let faces = [ + [corners[0], corners[1], corners[2]], + [corners[0], corners[2], corners[3]], + [corners[1], corners[0], tip], + [corners[2], corners[1], tip], + [corners[3], corners[2], tip], + [corners[0], corners[3], tip], + ]; + for face in faces { + let n = (face[1] - face[0]).cross(face[2] - face[0]).normalized().unwrap(); + let first = mesh.positions.len() as u32; + mesh.positions.extend(face); + mesh.normals.extend([n; 3]); + mesh.triangles.push([first, first + 1, first + 2]); + mesh.tri_face.push(0); + } + scene.meshes[0].mesh = Arc::new(mesh); + scene.bounds = scene.meshes[0].mesh.bounds(); + (Vec3::new(0.9999, 0., 2.), -Vec3::Z) + } else { + (Vec3::new(9.9999, if case == 2 { 9.9999 } else { 0. }, 2.), Vec3::new(1., 0., -1.).normalized().unwrap()) + }; + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, origin, 0.); + scene::vector(&mut params, direction, 0.); + scene::vector(&mut params, Vec3::ZERO, 0.); + scene::vector(&mut params, -Vec3::Z, 0.); + scene::vector(&mut params, Vec3::new(0.001, 0., 0.), 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + let result = values[0]; + let expected_distance = if pyramid { 0.0002 } else { 0.0001 * 2.0_f32.sqrt() }; + assert!((values[1][0] - expected_distance).abs() < 3e-6, "case={case}: {:?}", values); + assert_eq!(result, if pyramid { [0., 0., 1., 1.] } else { [0., 1., 1., 1.] }, "pyramid={pyramid}"); + } +} + +#[test] +fn gpu_triangle_bound_away_rejects_rounded_behind_origin_hit() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("positive triangle oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("positive_triangle_reference"), + compilation_options: Default::default(), + cache: None, + }); + // Actual stored f32 tank-edge failure. Ray starts at the minimum x and moves + // away, yet the projected distance numerator previously rounded positive. + let vertices = [[218.38487_f32, -3.8715396, -86.], [220.27007, -2.9226143, 85.], [218.38487, -3.8715396, 85.]]; + let origin = [218.38487_f32, -3.871542, -67.5458]; + let direction = [-0.3121568_f32, -0.45083842, 0.8362433]; + for axis in 0..3 { + for sign in [-1.0, 1.0] { + let transform = + |v: [f32; 3]| Vec3::new(f64::from(v[axis]) * sign, f64::from(v[(axis + 1) % 3]) * sign, f64::from(v[(axis + 2) % 3]) * sign); + let points = vertices.map(transform); + let d = transform(direction); + let n = (points[1] - points[0]).cross(points[2] - points[0]).normalized().unwrap(); + let mesh = Mesh { positions: points.to_vec(), normals: vec![n; 3], triangles: vec![[0, 1, 2]], tri_face: vec![0], ..Default::default() }; + let mut scene = sphere_grid(white(), 2, 3); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + for positive in [false, true] { + // Close positive intersections remain admitted; no epsilon is used. + let o = if positive { (points[0] + points[1] + points[2]) / 3.0 - d * 0.001 } else { transform(origin) }; + let mut task = Task::new(context.clone(), scene.clone(), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, o, 0.); + scene::vector(&mut params, d, 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + assert_eq!(values[0][0], if positive { 1.0 } else { 0.0 }, "axis={axis} sign={sign} positive={positive}"); + } + } + } +} + +#[test] +fn gpu_oblique_coplanar_grazing_reflection_does_not_rehit() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("coplanar boundary oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("coplanar_boundary_reference"), + compilation_options: Default::default(), + cache: None, + }); + let a = Vec3::new(f64::from(191.3_f32), f64::from(79.2_f32), f64::from(84.7_f32)); + let points = [a, a + Vec3::new(8., 0., 2.), a + Vec3::new(8., 8., 6.), a + Vec3::new(0., 8., 4.)]; + let n = Vec3::new(-0.25, -0.5, 1.).normalized().unwrap(); + let d = Vec3::new(f64::from(-0.69632584_f32), f64::from(0.69628024_f32), f64::from(0.17413844_f32)); + assert!(n.dot(d) > 0.0, "outward reflection"); + let mesh = + Mesh { positions: points.to_vec(), normals: vec![n; 4], triangles: vec![[0, 1, 2], [0, 2, 3]], tri_face: vec![0, 0], ..Default::default() }; + let mut scene = sphere_grid(white(), 2, 3); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, Vec3::new(f64::from(1.734274e-6_f32), f64::from(0.23548841_f32), 0.), 0.); + scene::vector(&mut params, d, 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + // A source point on this exact stored plane and an outward ray cannot hit + // its adjacent coplanar triangle at any strictly positive distance. + assert_eq!(values[0][0], 0.0, "hit/distance={:?}, reconstructed={:?}", values[0], values[1]); +} + +#[test] +fn gpu_shadow_closed_corner_keeps_short_exit_segment() { + let Some(executor) = executor() else { return }; + let mut scene = glass_slab(false); + let optics = scene.meshes[0].transmission.unwrap().with_shadow_transmission(true); + scene.meshes[0].transmission = Some(optics); + let cosine = std::f64::consts::FRAC_1_SQRT_2; + let actual = shadow_probe(&executor.context, scene, Vec3::new(8.4999, 0., 2.), Vec3::new(cosine, 0., -cosine), 4.); + let expected = solidcraft_render::transmission::solid_shadow(optics, 0.0001 * 2.0_f64.sqrt(), cosine, cosine, 1.5).unwrap(); + assert_eq!(actual[1][1], 2.0, "{actual:?}"); + for (a, b) in actual[0].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5, "{actual:?} vs {expected:?}"); + } +} + +#[test] +fn gpu_shadow_endpoint_near_interfaces_uses_true_distance() { + let Some(executor) = executor() else { return }; + let mut scene = glass_slab(false); + let optics = scene.meshes[0].transmission.unwrap().with_shadow_transmission(true); + scene.meshes[0].transmission = Some(optics); + // shadow_probe deliberately uses epsilon .01. Both offsets are smaller + // than its old 2epsilon cutoff, and must still classify the actual endpoint. + for (limit, length, factor, crossings) in + [(1.495, 0.0, 1.0, 0.0), (1.505, 0.005, 0.96 / 2.25, 1.0), (2.495, 0.995, 0.96 / 2.25, 1.0), (2.505, 1.0, 0.96 * 0.96, 2.0)] + { + let actual = shadow_probe(&executor.context, scene.clone(), Vec3::new(0., 0., 2.), -Vec3::Z, limit); + let expected = optics.attenuation(length).unwrap() * factor; + assert_eq!(actual[1][1], crossings, "limit={limit}: {actual:?}"); + for (a, b) in actual[0].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - b).abs() < 2e-5, "limit={limit}: {actual:?} vs {expected:?}"); + } + } +} + +#[test] +fn gpu_long_ray_thin_corner_orders_entry_before_exit() { + let Some(executor) = executor() else { return }; + let origin = Vec3::new(f64::from(f32::from_bits(0x43ad5626)), f64::from(f32::from_bits(0x44737912)), f64::from(f32::from_bits(0xc2dd2710))); + let direction = Vec3::new(f64::from(f32::from_bits(0xbe341340)), f64::from(f32::from_bits(0xbf762fdb)), f64::from(f32::from_bits(0x3e577470))); + // Captured stored-f32 tank side entry and top exit. Independent f64 plane + // distances are 929.5224413721813 and 929.5225421330013 respectively. + let side = [Vec3::new(243., 80., -86.), Vec3::new(157., 80., 85.), Vec3::new(243., 80., 85.)]; + let top = [Vec3::new(157., 80., 85.), Vec3::new(160., 77., 85.), Vec3::new(243., 80., 85.)]; + assert_entry_before_exit(&executor.context, origin, direction, side, top); +} + +#[test] +fn gpu_camera_ray_sharp_rim_tie_orders_entry_before_exit() { + let Some(executor) = executor() else { return }; + let origin = Vec3::new(f64::from(f32::from_bits(0xc409ad54)), f64::from(f32::from_bits(0xc45c5451)), f64::from(f32::from_bits(0x44160000))); + let direction = Vec3::new(f64::from(f32::from_bits(0x3eac85fe)), f64::from(f32::from_bits(0x3f3d52db)), f64::from(f32::from_bits(0xbf152b54))); + // Captured 64-spp coffee camera ray across the bin rim. Exact ray + // parameters are 1124.0922606444 (entry) and 1124.0923198562 (exit): + // closer than one f32 ULP, and both rounded to one scaled distance. + let bottom = [Vec3::new(-152., -50., -55.), Vec3::new(-212., -50., -55.), Vec3::new(-182., -53., -55.)]; + let side = [Vec3::new(-152., -50., -55.), Vec3::new(-152., -50., -124.), Vec3::new(-212., -50., -55.)]; + assert_entry_before_exit(&executor.context, origin, direction, bottom, side); +} + +#[test] +fn gpu_exact_rim_tie_prefers_entry_from_outside() { + let Some(executor) = executor() else { return }; + // The ray crosses the shared rim edge itself: both faces report the same + // exact depth, so only the medium-state tie preference can order them. + let top = [Vec3::new(0., 0., 0.), Vec3::new(0.5, -1., 0.), Vec3::new(1., 0., 0.)]; + let side = [Vec3::new(0., 0., 0.), Vec3::new(1., 0., 0.), Vec3::new(0.5, 0., -1.)]; + assert_entry_before_exit(&executor.context, Vec3::new(0.25, -4., 4.), Vec3::new(0., 1., -1.), top, side); +} + +fn assert_entry_before_exit(context: &Arc, origin: Vec3, direction: Vec3, entry: [Vec3; 3], exit: [Vec3; 3]) { + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("long-ray ordering oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("ordering_reference"), + compilation_options: Default::default(), + cache: None, + }); + for permutation in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] { + let odd = (permutation[0] > permutation[1]) ^ (permutation[0] > permutation[2]) ^ (permutation[1] > permutation[2]); + for reflection in 0..8_u32 { + let sign = |axis: u32| if reflection & (1 << axis) == 0 { 1.0 } else { -1.0 }; + let transform = |v: Vec3| { + let a = [v.x, v.y, v.z]; + Vec3::new(a[permutation[0]] * sign(0), a[permutation[1]] * sign(1), a[permutation[2]] * sign(2)) + }; + let invert = odd ^ (reflection.count_ones() % 2 != 0); + for reverse in [false, true] { + let mut mesh = Mesh::default(); + for face in if reverse { [exit, entry] } else { [entry, exit] } { + let mut face = face.map(transform); + if invert { + face.swap(1, 2); + } + let n = (face[1] - face[0]).cross(face[2] - face[0]).normalized().unwrap(); + let i = mesh.positions.len() as u32; + mesh.positions.extend(face); + mesh.normals.extend([n; 3]); + mesh.triangles.push([i, i + 1, i + 2]); + mesh.tri_face.push(0); + } + let mut scene = sphere_grid(white(), 2, 3); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, transform(origin), 0.); + scene::vector(&mut params, transform(direction), 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + assert_eq!( + values[0][0], + if reverse { 1.0 } else { 0.0 }, + "permutation={permutation:?}, reflection={reflection}, reverse={reverse}, best/candidates={values:?}" + ); + assert_eq!(values[1][1], 1.0, "candidate0 rejected: {values:?}"); + assert_eq!(values[2][1], 1.0, "candidate1 rejected: {values:?}"); + } + } + } +} +#[test] +fn gpu_far_rib_reentry_near_an_edge_is_not_lost_between_paths() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("rib re-entry oracle"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("continuation_reference"), + compilation_options: Default::default(), + cache: None, + }); + let bits = |x: u32, y: u32, z: u32| Vec3::new(f64::from(f32::from_bits(x)), f64::from(f32::from_bits(y)), f64::from(f32::from_bits(z))); + // Captured stored-f32 faces of the coffee bin's ribbed wall: the producing + // face, its nearby neighbour, the far re-entry face sharing the neighbour's + // edge, and the next exit. The ray leaves the producing face and truly + // re-enters 2.615 mm later, inside the re-entry face but very close to the + // shared edge; it then exits 17.529 mm along. + let faces = [ + [bits(0x438a6e62, 0x4175ca91, 0xc2860000), bits(0x4389b018, 0x416145f8, 0x42c80000), bits(0x438a6e62, 0x4175ca91, 0x42c80000)], + [bits(0x438b2463, 0x4185b9d0, 0xc2860000), bits(0x438a6e62, 0x4175ca91, 0x42c80000), bits(0x438b2463, 0x4185b9d0, 0x42c80000)], + [bits(0x438b2463, 0x4185b9d0, 0xc2860000), bits(0x438b2463, 0x4185b9d0, 0x42c80000), bits(0x438bd1ab, 0x419119e4, 0xc2860000)], + [bits(0x43906f8f, 0x41d4ebca, 0xc28e0000), bits(0x43906f8f, 0x41d4ebca, 0x42c80000), bits(0x438ff618, 0x41c5d6eb, 0xc28e0000)], + ]; + let mut mesh = Mesh::default(); + for face in faces { + let n = (face[1] - face[0]).cross(face[2] - face[0]).normalized().unwrap(); + let i = mesh.positions.len() as u32; + mesh.positions.extend(face); + mesh.normals.extend([n; 3]); + mesh.triangles.push([i, i + 1, i + 2]); + mesh.tri_face.push(0); + } + let mut scene = sphere_grid(white(), 2, 3); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, bits(0x438a6e62, 0x4175ca91, 0xc2860000), 0.); + scene::vector(&mut params, bits(0xbedb21b8, 0xbebd05fd, 0x4295df13), 0.); + scene::vector(&mut params, bits(0x3f3519ed, 0x3f28acac, 0xbe82f446), 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + assert_eq!(values[0][0], 2.0, "hit/distance={:?}", values[0]); + assert!((f64::from(values[0][1]) - 2.615).abs() < 0.01, "hit/distance={:?}", values[0]); +} +#[test] +fn gpu_entry_at_a_shared_edge_does_not_reenter_the_adjacent_face() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("edge entry oracle"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("continuation_reference"), + compilation_options: Default::default(), + cache: None, + }); + let bits = |x: u32, y: u32, z: u32| Vec3::new(f64::from(f32::from_bits(x)), f64::from(f32::from_bits(y)), f64::from(f32::from_bits(z))); + // Captured tumbler faces: a refracted ray entered the glass through the first + // face 8e-9 (barycentric) from its edge with the second. Its reconstructed + // start is 6.5e-9 mm outside both planes, so it met the second face from + // outside 1.1e-8 mm later: an "entry" while already inside. A cone to an + // apex behind both faces closes the captured pair into valid closed glass. + let a = bits(0x43050000, 0x42095be6, 0x42140000); + let b = bits(0x4304aef7, 0x4218aea0, 0x41b80000); + let c = bits(0x4303bd40, 0x4205b1dd, 0x41b80000); + let e = bits(0x4305c374, 0x421b114d, 0x42140000); + let f = Vec3::new(140.75, 34.75, 29.5); + let faces = [[c, a, b], [e, b, a], [a, c, f], [e, a, f], [b, e, f], [c, b, f]]; + let mut mesh = Mesh::default(); + for face in faces { + let n = (face[1] - face[0]).cross(face[2] - face[0]).normalized().unwrap(); + let i = mesh.positions.len() as u32; + mesh.positions.extend(face); + mesh.normals.extend([n; 3]); + mesh.triangles.push([i, i + 1, i + 2]); + mesh.tri_face.push(0); + } + let mut scene = glass_slab(false); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, bits(0x43050000, 0x42095be6, 0x42140000), 1.); + scene::vector(&mut params, bits(0xbda74978, 0x3f7d0fd4, 0xc06735c3), 0.); + scene::vector(&mut params, bits(0x3f4ff9cf, 0x3f0c3c0f, 0xbe4c997d), 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + // The ray must leave through one of the closing faces, at a real distance. + assert!(values[0][0] >= 2.0 && values[0][0] < 6.0, "hit/distance={:?}", values[0]); + assert!(values[0][1] > 1e-3, "hit/distance={:?}", values[0]); +} +#[test] +fn gpu_long_ray_near_corner_refraction_keeps_real_exit() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("refracted corner oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("refracted_corner_reference"), + compilation_options: Default::default(), + cache: None, + }); + let origin = Vec3::new(f64::from(f32::from_bits(0x43ad5626)), f64::from(f32::from_bits(0x44737912)), f64::from(f32::from_bits(0xc2dd2710))); + let direction = Vec3::new(f64::from(f32::from_bits(0xbe341340)), f64::from(f32::from_bits(0xbf762fdb)), f64::from(f32::from_bits(0x3e577470))); + let ior = f64::from(1.586_f32); + let ni = direction.x / ior; + let nk = direction.z / ior; + let refracted = Vec3::new(ni, -(1.0 - ni * ni - nk * nk).sqrt(), nk); + let entry_distance = (80.0 - origin.y) / direction.y; + let entry_z = origin.z + direction.z * entry_distance; + let exit_distance = (85.0 - entry_z) / refracted.z; + // Independent f64 plane/refraction oracle: true entry clearance is ~21um. + assert!(85.0 - entry_z > 0.00002 && 85.0 - entry_z < 0.000022); + let faces = [ + [[157., 0., 85.], [243., 0., 85.], [243., 80., 85.], [157., 80., 85.]], + [[157., 80., -86.], [243., 80., -86.], [243., 0., -86.], [157., 0., -86.]], + [[243., 80., -86.], [157., 80., -86.], [157., 80., 85.], [243., 80., 85.]], + [[157., 0., -86.], [243., 0., -86.], [243., 0., 85.], [157., 0., 85.]], + [[243., 0., -86.], [243., 80., -86.], [243., 80., 85.], [243., 0., 85.]], + [[157., 80., -86.], [157., 0., -86.], [157., 0., 85.], [157., 80., 85.]], + ]; + for permutation in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] { + let odd = (permutation[0] > permutation[1]) ^ (permutation[0] > permutation[2]) ^ (permutation[1] > permutation[2]); + for reflection in 0..8_u32 { + let sign = |axis: u32| if reflection & (1 << axis) == 0 { 1.0 } else { -1.0 }; + let transform = |v: Vec3| { + let a = [v.x, v.y, v.z]; + Vec3::new(a[permutation[0]] * sign(0), a[permutation[1]] * sign(1), a[permutation[2]] * sign(2)) + }; + let invert = odd ^ (reflection.count_ones() % 2 != 0); + let mut mesh = Mesh::default(); + for face in faces { + for indices in [[0, 1, 2], [0, 2, 3]] { + let mut p = indices.map(|i| { + let a = face[i]; + transform(Vec3::new(a[0], a[1], a[2])) + }); + if invert { + p.swap(1, 2); + } + let n = (p[1] - p[0]).cross(p[2] - p[0]).normalized().unwrap(); + let i = mesh.positions.len() as u32; + mesh.positions.extend(p); + mesh.normals.extend([n; 3]); + mesh.triangles.push([i, i + 1, i + 2]); + mesh.tri_face.push(0); + } + } + let mut scene = glass_slab(false); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0., 0.1, ior).unwrap()); + scene.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap()); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, transform(origin), 0.); + scene::vector(&mut params, transform(direction), 0.); + scene::vector(&mut params, Vec3::ZERO, 0.); + scene::vector(&mut params, Vec3::ZERO, 0.); + scene::vector(&mut params, Vec3::new(0.00084, 0., 0.), 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + assert_eq!(values[0], [1.; 4], "permutation={permutation:?} reflection={reflection}: {values:?}"); + let z_axis = permutation.iter().position(|axis| *axis == 2).unwrap(); + assert!(values[2][z_axis] < 85.0, "rounded entry onto top edge: {values:?}"); + // Two position ULP at z85, propagated through the refracted angle. + let tolerance = 2.0 * f64::from(f32::from_bits(85.0_f32.to_bits() + 1) - 85.0) / refracted.z; + assert!( + (f64::from(values[1][0]) - exit_distance).abs() < tolerance, + "distance={:?} expected={exit_distance} tolerance={tolerance}", + values[1] + ); + let expected = transform(refracted); + for (a, b) in values[3].iter().zip([expected.x, expected.y, expected.z]) { + assert!((f64::from(*a) - 2.0 - b).abs() < 2e-6); + } + } + } +} +#[test] +fn gpu_rib_total_internal_reflection_retains_origin_residual() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("rib residual oracle"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("rib_residual_reference"), + compilation_options: Default::default(), + cache: None, + }); + let a = Vec3::new(-162., -53., -127.); + let b = Vec3::new(f64::from(-163.7_f32), -55., -55.); + let c = Vec3::new(f64::from(-163.7_f32), -55., -127.); + let other = Vec3::new(-165.5, -53., -55.); + let bary = Vec3::new(f64::from(f32::from_bits(0x369bafd4)), f64::from(f32::from_bits(0x3f59c40b)), f64::from(f32::from_bits(0x3e18ee9d))); + let incoming = Vec3::new(f64::from(f32::from_bits(0xbeba12cc)), f64::from(f32::from_bits(0xbf6e1a19)), f64::from(f32::from_bits(0xbd5b2b1e))); + // These are captured GPU barycentrics, not an idealized primary-ray hit. + let point = b + (a - b) * bary.x + (c - b) * bary.z; + let normal = (b - a).cross(c - a).normalized().unwrap(); + let outgoing = incoming - normal * (2.0 * incoming.dot(normal)); + let exit_normal = (other - b).cross(c - b).normalized().unwrap(); + let expected = -(point - b).dot(exit_normal) / outgoing.dot(exit_normal); + assert!(expected > 1e-5 && expected < 1.5e-5); + let cross_section = [[-162., -53.], [f64::from(-163.7_f32), -55.], [-165.5, -53.]]; + let mut faces = Vec::new(); + let lower = cross_section.map(|p| Vec3::new(p[0], p[1], -127.)); + let upper = cross_section.map(|p| Vec3::new(p[0], p[1], -55.)); + faces.push(lower); + faces.push([upper[0], upper[2], upper[1]]); + for i in 0..3 { + let j = (i + 1) % 3; + faces.push([lower[i], upper[i], upper[j]]); + faces.push([lower[i], upper[j], lower[j]]); + } + for permutation in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] { + let odd = (permutation[0] > permutation[1]) ^ (permutation[0] > permutation[2]) ^ (permutation[1] > permutation[2]); + for reflection in 0..8_u32 { + let sign = |axis: u32| if reflection & (1 << axis) == 0 { 1.0 } else { -1.0 }; + let transform = |v: Vec3| { + let a = [v.x, v.y, v.z]; + Vec3::new(a[permutation[0]] * sign(0), a[permutation[1]] * sign(1), a[permutation[2]] * sign(2)) + }; + let invert = odd ^ (reflection.count_ones() % 2 != 0); + let mut mesh = Mesh::default(); + for face in &faces { + let mut p = face.map(transform); + if invert { + p.swap(1, 2); + } + let n = (p[1] - p[0]).cross(p[2] - p[0]).normalized().unwrap(); + let i = mesh.positions.len() as u32; + mesh.positions.extend(p); + mesh.normals.extend([n; 3]); + mesh.triangles.push([i, i + 1, i + 2]); + mesh.tri_face.push(0); + } + let mut scene = glass_slab(false); + scene.bounds = mesh.bounds(); + scene.meshes[0].mesh = Arc::new(mesh); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0., 0.1, f64::from(1.49_f32)).unwrap()); + scene.meshes[0].transmission = Some(solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap()); + let mut task = Task::new(context.clone(), scene, request(2), JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, transform(a), 0.); + scene::vector(&mut params, transform(if invert { c } else { b }), 0.); + scene::vector(&mut params, transform(if invert { b } else { c }), 0.); + scene::vector(&mut params, transform(incoming), 0.); + scene::vector(&mut params, Vec3::new(0.00084, 0., 0.), 0.); + scene::vector(&mut params, if invert { Vec3::new(bary.x, bary.z, bary.y) } else { bary }, 0.); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + assert_eq!(values[0], [0., 1., 1., 1.], "permutation={permutation:?} reflection={reflection}: {values:?}"); + assert_eq!(values[1][1], 1.0, "must be TIR: {values:?}"); + assert!((f64::from(values[1][0]) - expected).abs() < 2e-7, "expected={expected}: {values:?}"); + } + } +} +#[test] +fn gpu_integer_binary32_add_sub_matches_hardware_bits() { + use wgpu::util::DeviceExt; + let Some(executor) = executor() else { return }; + let context = &executor.context; + let mut pairs = Vec::new(); + let fractions = [0, 1, 0x3fffff, 0x400000, 0x400001, 0x7ffffe, 0x7fffff]; + for exponent in [0u32, 1, 2, 23, 24, 25, 31, 32, 63, 126, 127, 128, 253, 254, 255] { + for gap in [0, 1, 23, 24, 25, 31, 32, 63, 254] { + for a_fraction in fractions { + for b_fraction in fractions { + let a = exponent << 23 | a_fraction; + let b = exponent.saturating_sub(gap) << 23 | b_fraction; + pairs.extend([[a, b], [a ^ 0x80000000, b], [b, a], [b, a ^ 0x80000000]]); + } + } + } + } + pairs.extend([[0x80000000, 0x80000000], [0, 0x80000000], [1, 0x80000001]]); + let mut state = 0x9e3779b9u32; + while pairs.len() < 65536 { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + let a = state; + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + pairs.push([a, state]); + } + assert_eq!(pairs.len(), 65536); + let mut bytes = Vec::with_capacity(4 + pairs.len() * 8); + bytes.extend((pairs.len() as u32).to_le_bytes()); + for pair in &pairs { + for word in pair { + bytes.extend(word.to_le_bytes()); + } + } + let input = context.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("integer binary32 inputs"), + contents: &bytes, + usage: wgpu::BufferUsages::STORAGE, + }); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("integer binary32 oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &shader, + entry_point: Some("integer_float_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), glass_slab(false), request(256), JobOptions::default(), CancelToken::default()).unwrap(); + let bind = context.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("integer binary32 oracle"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: task.accumulation.as_entire_binding() }, + ], + }); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(1024, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + let bits = |value: f32| if value.is_nan() { 0x7fc00000 } else { value.to_bits() }; + for (i, ([a, b], value)) in pairs.iter().zip(values).enumerate() { + let a_float = f32::from_bits(*a); + let b_float = f32::from_bits(*b); + let sum = value[0] as u32 | (value[1] as u32) << 16; + let difference = value[2] as u32 | (value[3] as u32) << 16; + assert_eq!(sum, bits(a_float + b_float), "sum index={i} a={a:08x} b={b:08x}"); + assert_eq!(difference, bits(a_float - b_float), "difference index={i} a={a:08x} b={b:08x}"); + } +} +#[test] +fn gpu_emitter_short_segment_beer_and_area_pdf() { + let Some(executor) = executor() else { return }; + let context = &executor.context; + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("short emitter segment oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("emitter_segment_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), glass_slab(false), request(1), JobOptions::default(), CancelToken::default()).unwrap(); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let result = task.read_linear().unwrap()[0]; + let ray = Vec3::new(f64::from(0.6f32), 0., f64::from(0.8f32)); + let distance = f64::from(0.00001f32); + let length = ray.len() * distance; + let cosine = ray.z / ray.len(); + let expected = [length, (-5000. * length).exp(), length * length / (16. * cosine)]; + for i in 0..3 { + assert!((f64::from(result[i]) / expected[i] - 1.).abs() < 2e-6, "channel={i} expected={expected:?} result={result:?}"); + } +} +#[test] +fn gpu_integer_relative_fast_paths_match_ordered_rounding() { + use wgpu::util::DeviceExt; + let Some(executor) = executor() else { return }; + let context = &executor.context; + let mut quads = Vec::new(); + let fractions = [0, 1, 0x3fffff, 0x400000, 0x400001, 0x7ffffe, 0x7fffff]; + for exponent in [0u32, 1, 2, 23, 24, 25, 126, 127, 128, 253, 254, 255] { + for fraction in fractions { + let a = exponent << 23 | fraction; + for b in [a, a ^ 1, a.wrapping_add(0x800000), a ^ 0x80000000, 0, 0x80000000] { + for offset in [0, 0x80000000, 1, 0x80000001, 0x3f800000, 0xbf800000, a, b] { + quads.extend([[a, 0, b, offset], [a, offset, b, 0], [a, offset, a, b], [a, b, b, a]]); + } + } + } + } + let mut state = 0x12345678u32; + while quads.len() < 65536 { + let mut next = || { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + state + }; + let mut quad = [next(), next(), next(), next()]; + match quads.len() % 5 { + 0 => quad[2] = quad[0], + 1 => { + quad[1] = 0; + quad[3] = 0; + } + 2 => quad[1] = 0, + 3 => { + quad[0] = 0x3f800000 | (quad[0] & 0x7fffff); + quad[2] = quad[0] ^ 1; + } + _ => {} + } + quads.push(quad); + } + assert_eq!(quads.len(), 65536); + let mut bytes = Vec::with_capacity(4 + quads.len() * 16); + bytes.extend((quads.len() as u32).to_le_bytes()); + for quad in &quads { + for word in quad { + bytes.extend(word.to_le_bytes()); + } + } + let input = context.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("relative coordinate inputs"), + contents: &bytes, + usage: wgpu::BufferUsages::STORAGE, + }); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("relative coordinate oracle"), + source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &shader, + entry_point: Some("integer_relative_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut task = Task::new(context.clone(), glass_slab(false), request(256), JobOptions::default(), CancelToken::default()).unwrap(); + let bind = context.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("relative coordinate oracle"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: task.accumulation.as_entire_binding() }, + ], + }); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(1024, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let values = task.read_linear().unwrap(); + for (i, (quad, value)) in quads.iter().zip(values).enumerate() { + let reference = value[0] as u32 | (value[1] as u32) << 16; + let candidate = value[2] as u32 | (value[3] as u32) << 16; + let [a, al, b, bl] = quad.map(f32::from_bits); + let anchor = a - b; + let offset = al - bl; + let result = anchor + offset; + let expected = if result.is_nan() { 0x7fc00000 } else { result.to_bits() }; + assert_eq!(reference, expected, "reference index={i} input={quad:08x?}"); + assert_eq!(candidate, expected, "candidate index={i} input={quad:08x?}"); + } +} + +#[test] +fn medium_failures_are_tolerated_only_when_rare() { + // One failure in one path (a camera inside glass) is never tolerated. + assert!(!medium_failures_tolerated(1, 1)); + assert!(medium_failures_tolerated(0, 1)); + assert!(medium_failures_tolerated(1, 1_000_000)); + assert!(!medium_failures_tolerated(2, 1_000_000)); + // 1080p at 256 spp tolerates up to 530 isolated paths. + assert!(medium_failures_tolerated(530, 1920 * 1080 * 256)); + assert!(!medium_failures_tolerated(531, 1920 * 1080 * 256)); + assert!(!medium_failures_tolerated(1_u64 << 32, 1_u64 << 32)); +} + +#[test] +fn identical_maps_pack_once_for_multiple_gpu_bodies() { + use solidcraft_render::job::textures::{PlanarFrame, RuntimeTextures}; + let fixture = texture_fixture(PlanarFrame { origin: [0.0; 3], u: [2.0, 0.0, 0.0], v: [0.0, 2.0, 0.0] }); + let first = fixture.bindings()[0].clone(); + let mut second = first.clone(); + second.body_index = 1; + second.body_name = "Second body".into(); + let input = RuntimeTextures::new(vec![first, second]).unwrap(); + let bytes = textures::flatten(Some(&input), 2, Vec3::ZERO, &CancelToken::default()).unwrap(); + let word = |i: usize| u32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().unwrap()) as usize; + let a = word(5); + let b = word(6); + assert_ne!(a, b, "bindings keep separate coordinate records"); + assert_eq!(word(a + 3), word(b + 3), "one color payload"); + assert_eq!(word(a + 12), word(b + 12), "one normal payload"); +} + +#[test] +fn gpu_scalar_maps_match_linear_reference_without_touching_ior() { + use image::ImageEncoder; + use solidcraft_render::{ + job::textures::{PlanarFrame, RuntimeTextures, TextureMap}, + texture_input::MapRole, + }; + let Some(executor) = executor() else { return }; + let context = &executor.context; + let scalar = |value: u8, role| { + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image(&[value, value, value, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap(); + TextureMap::new(bytes, role).unwrap() + }; + let fixture = texture_fixture(PlanarFrame { origin: [0.0; 3], u: [2.0, 0.0, 0.0], v: [0.0, 2.0, 0.0] }); + let mut binding = fixture.bindings()[0].clone(); + binding.base_color = None; + binding.normal = None; + binding.flip_v = true; + binding.roughness = Some(scalar(192, MapRole::Roughness)); + binding.metallic = Some(scalar(64, MapRole::Metallic)); + let source = Arc::new(RuntimeTextures::new(vec![binding]).unwrap()); + let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&context.layout)], + immediate_size: 0, + }); + let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: Some(&layout), + module: &shader, + entry_point: Some("texture_scalar_reference"), + compilation_options: Default::default(), + cache: None, + }); + let mut input = request(2); + input.textures = Some(source); + // An explicit non-default optical fixture catches accidental IOR rewrites. + let original = OpaqueSurface::new(Vec3::new(0.2, 0.4, 0.6), 0.6, 0.2, 1.7).unwrap(); + let mut task = Task::new(context.clone(), sphere(original), input, JobOptions::default(), CancelToken::default()).unwrap(); + let mut params = vec![0; 32]; + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, Vec3::ZERO, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + scene::vector(&mut params, Vec3::Z, 0.0); + context.queue.write_buffer(&task.uniform, 0, ¶ms); + let mut encoder = context.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &task.bind, &[]); + pass.dispatch_workgroups(1, 1, 1); + } + context.queue.submit([encoder.finish()]); + task.sample = 1; + let actual = task.read_linear().unwrap(); + for (a, b) in actual[0].iter().zip([64.0 / 255.0, 192.0 / 255.0, original.dielectric_ior()]) { + assert!((f64::from(*a) - b).abs() < 2e-6, "scalar map {actual:?}"); + } +} + +#[test] +fn production_envelope_is_device_bounded_and_never_silently_resized() { + let mut image = request(1); + image.width = 3840; + image.height = 2160; + let source = sphere(white()); + let accepted = admission(&source, &image, JobOptions::default()).unwrap(); + assert!(accepted.estimated_total_bytes < GPU_PATH_LIMITS.max_scratch_bytes); + assert_eq!(descriptor().unwrap().fit(3840, 2160), Some((3840, 2160))); + image.width = 8193; + assert!(admission(&source, &image, JobOptions::default()).is_err()); + image.width = 8192; + image.height = 8192; + assert!(admission(&source, &image, JobOptions::default()).is_err()); + let mut supported = wgpu::Limits::downlevel_defaults(); + supported.max_storage_buffers_per_shader_stage = 8; + supported.max_storage_buffer_binding_size = 2 * 1024 * 1024 * 1024; + supported.max_buffer_size = 2 * 1024 * 1024 * 1024; + let limits = device_limits(supported.clone()).unwrap(); + assert_eq!(limits.max_storage_buffer_binding_size, 1024 * 1024 * 1024); + assert!(limits.max_buffer_size <= supported.max_buffer_size); +} + +#[test] +fn disjoint_glass_count_does_not_relax_closed_topology_or_overlap_validation() { + let template = sphere_grid(white(), 8, 16); + let mut source = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + for i in 0..solidcraft_render::job::MAX_GPU_DIELECTRICS { + let mut body = template.meshes[0].clone(); + body.name = format!("separate glass {i}"); + for p in &mut Arc::make_mut(&mut body.mesh).positions { + p.x += i as f64 * 3.0; + } + body.transmission = Some(clear_glass()); + source.bounds = source.bounds.union(&body.mesh.bounds()); + source.meshes.push(body); + } + assert!(scene::flatten(&source, Vec3::ZERO, &CancelToken::default()).is_ok()); + source.meshes.push(source.meshes[0].clone()); + assert!(scene::flatten(&source, Vec3::ZERO, &CancelToken::default()).is_err()); +} + +#[test] +fn display_identity_matches_the_legacy_response_and_spatial_filters_ignore_chunking() { + use solidcraft_render::job::finishing::{Backdrop, BackdropMode, Finishing}; + let cancel = CancelToken::default(); + let input: Vec<[f32; 4]> = (0..91) + .map(|i| { + [ + i as f32 * 0.15, + 0.07, + 0.8, + if i % 3 == 0 { + 0.0 + } else if i % 3 == 1 { + 0.5 + } else { + 1.0 + }, + ] + }) + .collect(); + let display = Display { + finishing: Finishing::default(), + backdrop: None, + width: 13, + height: 7, + exposure: 1.3, + tone_map: ToneMap::Reinhard, + background: [0.02, 0.05, 0.12], + transparent: false, + }; + let mut reference = Vec::new(); + for pixel in &input { + let alpha = f64::from(pixel[3]); + for (radiance, background) in pixel.iter().take(3).zip(display.background) { + let c = if alpha > 0.0 { f64::from(*radiance) * display.exposure / alpha } else { 0.0 }; + let value = display.tone_map.map(c) * alpha + background * (1.0 - alpha); + let encoded = if value <= 0.0031308 { value * 12.92 } else { 1.055 * value.powf(1.0 / 2.4) - 0.055 }; + reference.push((encoded.clamp(0.0, 1.0) * 255.0).round() as u8); + } + reference.push(255); + } + let mut neutral = vec![0; input.len() * 4]; + display.encode(&input, &mut neutral, &cancel).unwrap(); + assert_eq!(neutral, reference); + let changed = Display { + finishing: Finishing { rgb_gain: [1.2, 0.9, 0.7], contrast: 1.2, saturation: 0.3, vignette: 0.45, ..Default::default() }, + backdrop: Some(Backdrop { mode: BackdropMode::Radial, ..Default::default() }), + ..display + }; + let mut all = vec![0; input.len() * 4]; + changed.encode(&input, &mut all, &cancel).unwrap(); + for chunk in [1, 5, 13, 90] { + let mut split = vec![0; all.len()]; + for (index, (pixels, output)) in input.chunks(chunk).zip(split.chunks_mut(chunk * 4)).enumerate() { + changed.encode_at(pixels, output, &cancel, index * chunk).unwrap(); + } + assert_eq!(all, split, "chunk {chunk} must preserve absolute vignette/backdrop position"); + } + assert_ne!(all, neutral); +} + +fn complete_linear_fixture(context: Arc, options: JobOptions) -> (Vec, Option>) { + // Use the public environment-lighting contract, not the test-only numerical + // furnace path. Primary misses remain transparent black in the linear master. + let options = JobOptions { + lighting: Some(solidcraft_render::job::StudioLighting { environment: [8.0; 3], sun: None, area_lights: Default::default() }), + ..options + }; + let mut task = Task::new(context, sphere(white()), request(16), options, CancelToken::default()).unwrap(); + for _ in 0..5000 { + match task.step(16384).unwrap() { + TaskPoll::Pending(_) => {} + TaskPoll::Complete(png) => { + let exr = task.take_linear_exr(); + assert!(task.take_linear_exr().is_none(), "linear master moves exactly once"); + return (png, exr); + } + } + } + panic!("bounded linear-output fixture did not finish") +} +#[test] +fn gpu_raw_master_keeps_hdr_samples_before_denoise_gain_tone_and_camera_backdrop() { + use solidcraft_render::job::finishing::{Backdrop, Finishing}; + let Some(executor) = executor() else { + return; + }; + let options = JobOptions { samples: 16, seed: 17, max_depth: 3, ..Default::default() }; + let (png, none) = complete_linear_fixture(executor.context.clone(), options); + assert!(none.is_none()); + let (retained, raw) = complete_linear_fixture(executor.context.clone(), JobOptions { linear_exr: true, ..options }); + assert_eq!(png, retained, "opting into raw retention does not change display pixels"); + let raw = raw.unwrap(); + let (filtered, other) = complete_linear_fixture( + executor.context.clone(), + JobOptions { + linear_exr: true, + denoise: true, + exposure_ev: -2.0, + tone_map: ToneMap::AcesFitted, + finishing: Finishing { rgb_gain: [1.4, 0.8, 0.6], saturation: 0.2, vignette: 0.4, ..Default::default() }, + backdrop: Some(Backdrop::default()), + ..options + }, + ); + assert_eq!(raw, other.unwrap(), "raw sample values precede every presentation adjustment"); + assert_ne!(png, filtered); + // Parse attributes/offsets independently to check real HDR data > display white. + let mut cursor = 8; + while raw[cursor] != 0 { + while raw[cursor] != 0 { + cursor += 1; + } + cursor += 1; + while raw[cursor] != 0 { + cursor += 1; + } + cursor += 1; + let size = i32::from_le_bytes(raw[cursor..cursor + 4].try_into().unwrap()) as usize; + cursor += 4 + size; + } + cursor += 1; + let mut maximum = 0_f32; + for y in 0..16 { + let offset = u64::from_le_bytes(raw[cursor + y * 8..cursor + y * 8 + 8].try_into().unwrap()) as usize; + for bytes in raw[offset + 8 + 64..offset + 8 + 256].as_chunks::<4>().0 { + maximum = maximum.max(f32::from_le_bytes(*bytes)); + } + } + assert!(maximum > 2.0, "raw highlight radiance must not be clipped or reconstructed from PNG: {maximum}"); + // Optional fresh external evidence folder for an independent OpenEXR reader. + if let Some(out) = std::env::var_os("SOLIDCRAFT_FINISHING_EVIDENCE_DIR") { + let out = std::path::PathBuf::from(out); + assert!(out.is_absolute() && !out.exists()); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("raw-radiance.exr"), &raw).unwrap(); + std::fs::write(out.join("neutral.png"), &png).unwrap(); + std::fs::write(out.join("filtered.png"), &filtered).unwrap(); + std::fs::write( + out.join("expected.json"), + serde_json::to_vec_pretty(&serde_json::json!({"width":16,"height":16, + "maximum_raw_rgb":maximum,"raw_identical_before_after_finishing":true,"png_neutral_identity":true, + "rgba_type":"FLOAT","encoding":"scene-linear sRGB/D65","alpha":"coverage-premultiplied"})) + .unwrap(), + ) + .unwrap(); + } +} + +#[test] +fn gpu_host_retains_linear_companion_under_the_same_exact_frame_lease() { + use solidcraft_render::job::{JobId, Phase}; + let Some(executor) = executor() else { + return; + }; + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + let id = JobId { session: 999, serial: 1, generation: 42 }; + let source = sphere(white()); + let req = request(8); + let base = host.admit(&source, &req, JobOptions::default()).unwrap(); + let options = JobOptions { samples: 4, linear_exr: true, ..Default::default() }; + let extra = host.admit(&source, &req, options).unwrap(); + assert_eq!(extra.estimated_total_bytes - base.estimated_total_bytes, solidcraft_render::job::linear_exr::encoded_limit(8, 8).unwrap()); + let handle = host.submit_with_options(id, 7, source.clone(), req.clone(), options).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + let frame = handle.frame().unwrap().unwrap(); + let bytes = frame.linear_exr().unwrap(); + assert_eq!(frame.linear_master_info().unwrap().bytes, bytes.len() as u64); + assert_eq!(status.linear_master.unwrap().sha256, frame.linear_master_info().unwrap().sha256); + assert!(host.admitted_bytes() >= frame.png().len() as u64 + bytes.len() as u64); + drop(handle); + assert!(host.admitted_bytes() > 0); + drop(frame); + // Cancellation/completion notification and worker-owned resource destruction + // are distinct events. Require the actual reservation to drain, without + // forcing premature release or changing the host's asynchronous contract. + let released_by = std::time::Instant::now() + std::time::Duration::from_secs(5); + while host.admitted_bytes() != 0 { + assert!(std::time::Instant::now() < released_by, "worker did not release its completed/cancelled reservation"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(host.admitted_bytes(), 0); + let handle = host.submit_with_options(JobId { serial: 2, ..id }, 7, source, req, JobOptions { samples: 4096, ..options }).unwrap(); + handle.cancel().unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Cancelled); + assert!(handle.frame().unwrap().is_none()); + drop(handle); + // Cancellation/completion notification and worker-owned resource destruction + // are distinct events. Require the actual reservation to drain, without + // forcing premature release or changing the host's asynchronous contract. + let released_by = std::time::Instant::now() + std::time::Duration::from_secs(5); + while host.admitted_bytes() != 0 { + assert!(std::time::Instant::now() < released_by, "worker did not release its completed/cancelled reservation"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn engine_exports_raw_master_from_the_exact_completed_job_without_png_conversion() { + use serde_json::json; + use solidcraft_render::job::{JobId, Phase}; + let Some(executor) = executor() else { + return; + }; + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + let mut s = solidcraft_engine::Session::default(); + s.register_render_job_host(host.clone()).unwrap(); + s.execute("solid.box", &json!({"length":2,"width":2,"height":1,"body_name":"Original output fixture"})).unwrap(); + let before = s.doc.to_json(); + let p = json!({"progressive":true,"samples":4,"linear_exr":true,"settings":{"width":12,"height":8}, + "finishing":{"saturation":0.4},"backdrop":{"mode":"horizontal"}}); + let checked = s.execute("render.preflight", &p).unwrap(); + assert_eq!(checked["options"]["linear_exr"], true); + let started = s.execute("render.start", &p).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = s.render_job_handle(id).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap().progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + let root = std::env::temp_dir().join(format!( + "solidcraft-linear-export-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir(&root).unwrap(); + let path = root.join("raw.exr"); + let png = root.join("display.png"); + let output = s.execute("render.export", &json!({"job":id,"path":path,"format":"exr"})).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), frame.linear_exr().unwrap()); + assert_eq!(output["linear_master"]["sha256"], frame.linear_master_info().unwrap().sha256); + assert_eq!(output["encoding"], "scene_linear_srgb_d65"); + assert_eq!(output["alpha"], "coverage_premultiplied"); + assert_eq!(output["linear_master"]["encoding"], output["encoding"]); + s.execute("render.export", &json!({"job":id,"path":png})).unwrap(); + assert_eq!(std::fs::read(&png).unwrap(), frame.png()); + assert!(s.execute("render.export", &json!({"job":id,"path":path,"format":"exr"})).is_err()); + assert!(s.execute("render.export", &json!({"job":id,"path":path,"format":"png","overwrite":true})).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), frame.linear_exr().unwrap()); + assert!(s.execute("render.export", &json!({"job":JobId{session:id.session+1,..id},"path":root.join("wrong.exr"),"format":"exr"})).is_err()); + assert!(!root.join("wrong.exr").exists()); + assert_eq!(s.doc.to_json(), before); + drop(s); + drop(handle); + assert!(host.admitted_bytes() > 0); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn gpu_bloom_changes_display_only_with_explicit_scratch_and_opaque_contract() { + use solidcraft_render::job::{bloom::Bloom, finishing::Finishing}; + let Some(executor) = executor() else { return }; + let options = JobOptions { samples: 16, seed: 17, max_depth: 3, linear_exr: true, ..Default::default() }; + let (png, raw) = complete_linear_fixture(executor.context.clone(), options); + let bloom = Bloom { strength: 0.4, threshold: 1.0, radius: 2 }; + let modified = JobOptions { finishing: Finishing { bloom: Some(bloom), ..Default::default() }, ..options }; + let a = admission(&sphere(white()), &request(16), options).unwrap(); + let b = admission(&sphere(white()), &request(16), modified).unwrap(); + assert_eq!(b.estimated_total_bytes - a.estimated_total_bytes, 16 * 16 * 24); + assert_eq!(b.pixel_scratch_bytes - a.pixel_scratch_bytes, 16 * 16 * 24); + let (glowing, untouched) = complete_linear_fixture(executor.context.clone(), modified); + assert_eq!(raw, untouched, "bloom cannot alter the retained linear master or original estimator"); + assert_ne!(png, glowing); + let (neutral, same) = complete_linear_fixture( + executor.context.clone(), + JobOptions { finishing: Finishing { bloom: Some(Bloom { strength: 0.0, ..bloom }), ..Default::default() }, ..options }, + ); + assert_eq!(png, neutral); + assert_eq!(raw, same); + let transparent = ImageRequest { transparent_background: true, ..request(16) }; + assert!(executor.admit(&sphere(white()), &transparent, modified).is_err()); + let decoded = image::load_from_memory(&glowing).unwrap().to_rgba8(); + assert!(decoded.pixels().all(|p| p.0[3] == 255)); +} + +#[path = "adaptive_tests.rs"] +mod adaptive_tests; + +#[path = "regrade_tests.rs"] +mod regrade_tests; +#[path = "volume_tests.rs"] +mod volume_tests; + +#[path = "resource_pack_tests.rs"] +mod resource_pack_tests; + +#[path = "optical_media_tests.rs"] +mod optical_media_tests; + +#[path = "effects_tests.rs"] +mod effects_tests; + +#[test] +fn display_bloom_slices_refuse_invalid_ranges_without_panicking() { + let pixels = [[1.0_f32, 2.0, 3.0]; 3]; + assert_eq!(bloom_chunk(Some(&pixels), 1, 2).unwrap().unwrap(), &pixels[1..3]); + assert!(bloom_chunk(Some(&pixels), 3, 0).unwrap().unwrap().is_empty()); + for (offset, count) in [(0, 4), (2, 2), (4, 0), (usize::MAX, 1), (1, usize::MAX)] { + let result = std::panic::catch_unwind(|| bloom_chunk(Some(&pixels), offset, count)); + assert!(result.expect("invalid retained image range must not panic").is_err()); + } + assert!(bloom_chunk(None, 0, 3).unwrap().is_none()); +} + +/// Cancellation in fallible HDR preparation must not drop three wgpu scopes in +/// forward order. Exercise the real preparation routine inside the guarded path, +/// then prove that the same device still accepts a fresh nested scope stack. +#[test] +fn cancelled_environment_preparation_unwinds_gpu_error_scopes() { + use solidcraft_render::lighting::environment::EnvironmentSource; + let Ok((_, device, _queue)) = open_headless() else { + let available = !crate::select::path_backends().is_empty(); + assert!(!available || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required Vulkan device unavailable"); + return; + }; + let mut image = request(1); + image.environment = Some(Arc::new(EnvironmentSource::hdr(original_hdr(), 0.0, 1.0, false).unwrap())); + let token = CancelToken::default(); + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + checked_creation(&device, || { + token.cancel(); + prepare_environment(&image, &token) + }) + })); + let error = outcome.expect("ordinary cancellation must not panic").unwrap_err(); + assert_eq!(error.code, ErrorCode::Cancelled); + checked(scopes(&device)).unwrap(); + let bytes = prepare_environment(&image, &CancelToken::default()).unwrap(); + let info = image.environment.as_ref().unwrap().info(); + assert_eq!(bytes.len(), 16 + info.width as usize * info.height as usize * 32); +} + +/// A denoiser allocation can fail after the outer resource scopes were opened. +/// Preserve its Result while draining every scope, not only the last one. +#[test] +fn failed_resource_creation_unwinds_gpu_error_scopes() { + let Ok((_, device, _queue)) = open_headless() else { + let available = !crate::select::path_backends().is_empty(); + assert!(!available || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required Vulkan device unavailable"); + return; + }; + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + checked_creation(&device, || -> Result<()> { Err(JobError::new(ErrorCode::LimitExceeded, "synthetic bounded allocation refusal")) }) + })); + let error = outcome.expect("ordinary allocation refusal must not panic").unwrap_err(); + assert_eq!(error.code, ErrorCode::LimitExceeded); + checked(scopes(&device)).unwrap(); +} + +#[test] +fn actual_first_gpu_quantum_is_small_and_cancellation_retains_no_completed_image() { + let Some(executor) = executor() else { return }; + let token = CancelToken::default(); + let mut task = Task::new(executor.context.clone(), sphere(white()), request(64), JobOptions::default(), token.clone()).unwrap(); + task.dispatch().unwrap(); + assert_eq!(task.offset, dispatch::MIN_PATHS); + assert_eq!(task.sample, 0); + token.cancel(); + assert_eq!(task.step(4096).err().unwrap().code, ErrorCode::Cancelled); + assert!(task.png.is_none()); +} + +#[test] +fn real_device_loss_retires_the_executor_and_the_sessions_cached_availability() { + use solidcraft_engine::Session; + let Some(executor) = executor() else { return }; + let context = executor.context.clone(); + let host = ImageHost::with_executor(Arc::new(executor)).unwrap(); + let mut session = Session::default(); + session.register_render_job_host(host.clone()).unwrap(); + assert!(matches!(host.descriptor().unwrap().availability, Availability::Available)); + context.device.destroy(); + let deadline = Instant::now() + Duration::from_secs(2); + while context.healthy.load(Ordering::Acquire) && Instant::now() < deadline { + let _ = context.device.poll(wgpu::PollType::Poll); + std::thread::yield_now(); + } + assert!(!context.healthy.load(Ordering::Acquire), "actual device-loss callback must retire the host"); + assert!(matches!(host.descriptor().unwrap().availability, Availability::Unavailable { .. })); + let scene = sphere(white()); + assert_eq!(host.admit(&scene, &request(1), JobOptions::default()).unwrap_err().code, ErrorCode::HostUnavailable); + let backend = session.render_backend(); + assert!(backend.executors.iter().any(|d| d.id.as_str() == "gpu-path" && matches!(d.availability, Availability::Unavailable { .. }))); +} +#[test] +fn direct_gpu_admission_refuses_explicit_raster_rigs_even_when_empty() { + let mut input = request(16); + input.raster_lights = Some(Vec::new()); + let error = admission(&sphere(white()), &input, JobOptions::default()).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert!(error.message.contains("Raster lights")); +} + +#[test] +fn direct_gpu_admission_refuses_raster_only_exposure_without_opening_a_device() { + for ev in [-1.0, 1.0, f64::NAN] { + let mut input = request(16); + input.raster_exposure_ev = ev; + let error = admission(&sphere(white()), &input, JobOptions::default()).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert!(error.message.contains("Raster exposure")); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/examples/cpu_resource_smoke.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/examples/cpu_resource_smoke.rs new file mode 100644 index 000000000..e1647108f --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/examples/cpu_resource_smoke.rs @@ -0,0 +1,193 @@ +//! Bounded native acceptance probe for explicit CPU profiles. This is not a speed +//! benchmark or an application/UI test. Writes only to a new caller-selected folder. +use serde_json::json; +use solidcraft_geom::{Mesh, Vec3}; +use solidcraft_render::job::{CpuBudget, CpuHost, DirectionalLightOptions, ImageRequest, Integrator, JobId, JobOptions, Phase, RaytraceOptions}; +use solidcraft_render::{Camera, ProductMesh, ProductScene, StandardView, surface::OpaqueSurface}; +use std::{error::Error, fs, path::PathBuf, sync::Arc, time::Duration}; + +fn scene() -> Result> { + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -15.0, 0.0), Vec3::new(20.0, -15.0, 0.0), Vec3::new(20.0, 15.0, 0.0), Vec3::new(-20.0, 15.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + Ok(ProductScene { + bounds: mesh.bounds(), + meshes: vec![ProductMesh { + name: "Original CPU admission plate".into(), + mesh, + color: [92, 150, 210], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.1, 0.3, 0.6), 0.0, 0.5, 1.5)?), + transmission: None, + faces: Vec::new(), + }], + }) +} +fn request(width: u32, height: u32, budget: CpuBudget) -> ImageRequest { + let mut camera = Camera { distance: 65.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + budget, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]), + shadows: false, + ..Default::default() + }), + camera, + width, + height, + background: [236, 240, 245], + transparent_background: false, + } +} +fn dense_scene() -> Result> { + let side = 500u32; + let vertices = (side + 1) * (side + 1); + let mut positions = Vec::new(); + positions.try_reserve_exact(vertices as usize)?; + for y in 0..=side { + for x in 0..=side { + positions.push(Vec3::new(-20.0 + 40.0 * f64::from(x) / f64::from(side), -15.0 + 30.0 * f64::from(y) / f64::from(side), 0.0)); + } + } + let mut triangles = Vec::new(); + triangles.try_reserve_exact((2 * side * side) as usize)?; + for y in 0..side { + for x in 0..side { + let a = y * (side + 1) + x; + let b = a + 1; + let c = a + side + 2; + let d = a + side + 1; + triangles.push([a, b, c]); + triangles.push([a, c, d]); + } + } + let mesh = + Arc::new(Mesh { positions, normals: vec![Vec3::Z; vertices as usize], tri_face: vec![0; triangles.len()], triangles, ..Default::default() }); + let mut result = scene()?; + result.bounds = mesh.bounds(); + let body = result.meshes.first_mut().ok_or("missing fixture body")?; + body.mesh = mesh; + body.name = "Original 500000-triangle grid".into(); + Ok(result) +} +fn body_scene() -> Result> { + let mut result = scene()?; + let template = result.meshes.first().cloned().ok_or("missing fixture body")?; + result.meshes.clear(); + result.meshes.try_reserve_exact(20_000)?; + for y in 0..100 { + for x in 0..200 { + let (x, y) = (f64::from(x) - 99.5, f64::from(y) - 49.5); + let mesh = Arc::new(Mesh { + positions: vec![ + Vec3::new(x - 0.4, y - 0.4, 0.0), + Vec3::new(x + 0.4, y - 0.4, 0.0), + Vec3::new(x + 0.4, y + 0.4, 0.0), + Vec3::new(x - 0.4, y + 0.4, 0.0), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + let mut body = template.clone(); + body.name = format!("Original tile {x} {y}"); + body.mesh = mesh; + result.meshes.push(body); + } + } + result.bounds = solidcraft_geom::Aabb3 { min: Vec3::new(-100.0, -50.0, 0.0), max: Vec3::new(100.0, 50.0, 0.0) }; + Ok(result) +} + +fn main() -> Result<(), Box> { + let out = std::env::args_os().nth(1).map(PathBuf::from).ok_or("usage: cpu_resource_smoke NEW_OUTPUT_DIRECTORY [4k|8k|dense|bodies]")?; + fs::create_dir(&out)?; + let host = CpuHost::for_platform()?; + let case = std::env::args().nth(2).unwrap_or_else(|| "4k".into()); + let (width, height, budget, source) = match case.as_str() { + "4k" => (3840, 2160, CpuBudget::Studio, scene()?), + "8k" => (7680, 4320, CpuBudget::Workstation, scene()?), + "dense" => (256, 256, CpuBudget::Studio, dense_scene()?), + "bodies" => (512, 256, CpuBudget::Studio, body_scene()?), + _ => return Err("case must be 4k, 8k, dense or bodies".into()), + }; + let compact = request(width, height, CpuBudget::Compact); + if host.admit(&source, &compact, JobOptions::default()).is_ok() { + return Err("legacy Compact incorrectly admitted a deliberately oversized request".into()); + } + let mut studio = request(width, height, budget); + if case == "bodies" { + studio.camera.fit(&source.bounds); + } + let admission = host.admit(&source, &studio, JobOptions::default())?; + let id = JobId { session: 20261022, serial: 1, generation: 1 }; + let handle = host.submit(id, 1, source.clone(), studio)?; + let status = match handle.wait_timeout(Duration::from_secs(300)) { + Ok(status) => status, + Err(error) => { + let _ = handle.cancel(); + return Err(error.into()); + } + }; + if status.progress.phase != Phase::Completed { + return Err(format!("CPU render failed: {:?}", status.error).into()); + } + let frame = handle.frame()?.ok_or("completed CPU result has no frame")?; + let image = image::load_from_memory(frame.png())?.to_rgba8(); + if image.dimensions() != (width, height) || !image.pixels().any(|pixel| pixel.0 != [236, 240, 245, 255]) { + return Err("image does not contain the original analytic fixture".into()); + } + fs::write(out.join(format!("cpu-{case}.png")), frame.png())?; + let frame_info = serde_json::to_value(&frame.info)?; + drop(frame); + drop(handle); + // Native cleanup is observed through reservations; no capacity is claimed merely + // from a dimensions constant or a downscaled display texture. + for _ in 0..100 { + if host.admitted_bytes() == 0 { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + if host.admitted_bytes() != 0 { + return Err("completed CPU frame reservation was not released".into()); + } + + // Synthetic cardinality probe only, not a heavy-assembly render benchmark. + let admission_scene = scene()?; + let template = admission_scene.meshes.first().ok_or("missing original plate")?; + let mut bodies = Vec::new(); + bodies.try_reserve_exact(20_000)?; + for i in 0..20_000 { + let mut body = template.clone(); + body.name = format!("Admission body {i}"); + bodies.push(body); + } + let many = ProductScene { bounds: admission_scene.bounds, meshes: bodies }; + if host.admit(&many, &request(16, 16, CpuBudget::Compact), JobOptions::default()).is_ok() { + return Err("Compact accepted too many bodies".into()); + } + let bodies_admission = host.admit(&many, &request(16, 16, CpuBudget::Studio), JobOptions::default())?; + let record = json!({"status":"PASS","scope":"native CPU selected-case execution plus separate bounded synthetic body admission","case":case,"rendered_bodies":source.meshes.len(),"rendered_triangles":admission.triangles, + "not_a_performance_benchmark":true,"application_ui_tested":false,"frame":frame_info, + "image_admission":admission,"twenty_thousand_bodies_admission":bodies_admission, + "retained_pool_bytes_after_drop":host.admitted_bytes(),"compact_refused_both_explicit_large_requests":true}); + fs::write(out.join("receipt.json"), serde_json::to_vec_pretty(&record)?)?; + println!("{}", serde_json::to_string_pretty(&record)?); + Ok(()) +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host.rs new file mode 100644 index 000000000..27f1a4fdf --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host.rs @@ -0,0 +1,2999 @@ +//! Caller-owned image execution host. One worker, two bounded queued inputs; browser pumping +//! uses the same incremental task without threads. Shared ownership never includes CAD state. + +use std::collections::VecDeque; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Condvar; +use std::sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, AtomicU64, Ordering}, +}; + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use super::{ + Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageExecutor, ImageRequest, ImageTask, ImageWork, Integrator, + JobError, JobId, JobOptions, Phase, Progress, Result, TaskPoll, admit, +}; +use crate::{ + Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout, +}; + +const MEMORY_LIMIT: u64 = 512 * 1024 * 1024; +const QUEUE_LIMIT: usize = 2; + +#[cfg(test)] +struct CpuExecutor; +#[cfg(test)] +impl ImageExecutor for CpuExecutor { + fn descriptor(&self) -> Result { + Ok(ExecutorDescriptor { + id: ExecutorId::new("cpu-product").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: Availability::Available, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: vec![crate::RenderFeature::Pbr], + }], + limits: RenderLimits::default(), + scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }) + } + + fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + if options != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU product does not support sampling or exposure controls")); + } + admit(scene, request) + } + fn begin(&self, scene: ProductScene, request: ImageRequest, _options: JobOptions, cancel: CancelToken) -> Result> { + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } +} + +// Completion notification precedes destruction of the worker's temporary handle. +// Lease tests join their owned, idle worker before checking exact retained bytes. +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +impl ImageHost { + pub(super) fn join_worker_for_test(&mut self) -> Result<()> { + self.0.shared.stop.store(true, Ordering::Release); + self.0.shared.wake.notify_all(); + let inner = Arc::get_mut(&mut self.0).ok_or_else(|| JobError::new(ErrorCode::Internal, "test must own its host"))?; + if let Some(worker) = inner._worker.take() { + worker.join().map_err(|_| JobError::new(ErrorCode::Internal, "test worker panicked"))?; + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "host_regrade_tests.rs"] +mod regrade_tests; +#[cfg(test)] +#[path = "host_tests.rs"] +mod tests; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HostKind { + NativeWorker, + Cooperative, +} + +struct Budget { + used: AtomicU64, + limit: u64, +} +pub(crate) struct Reservation { + budget: Arc, + bytes: u64, +} + +impl Budget { + fn reserve(self: &Arc, bytes: u64) -> Result { + let mut used = self.used.load(Ordering::Acquire); + loop { + let next = used.checked_add(bytes).filter(|n| *n <= self.limit).ok_or_else(|| { + JobError::new(ErrorCode::LimitExceeded, format!("image host admission pool is full ({} MiB)", self.limit / (1024 * 1024))) + })?; + match self.used.compare_exchange_weak(used, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break, + Err(current) => used = current, + } + } + Ok(Reservation { budget: self.clone(), bytes }) + } +} +impl Reservation { + /// Merge unique portions of one admission without a second pool debit. + fn merge_from(&mut self, donor: &mut Self) -> Result<()> { + if !Arc::ptr_eq(&self.budget, &donor.budget) { + return Err(JobError::new(ErrorCode::WrongOwner, "cannot merge different image admission pools")); + } + let bytes = self + .bytes + .checked_add(donor.bytes) + .filter(|v| *v <= self.budget.limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "image reservation merge overflow"))?; + self.bytes = bytes; + donor.bytes = 0; + Ok(()) + } + /// Transfer an already admitted portion without changing the pool's total. + /// CPU progressive admission includes every possible checkpoint up front. + fn split(&mut self, bytes: u64) -> Result { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "preview exceeds its prepaid reservation")); + } + self.bytes -= bytes; + Ok(Self { budget: self.budget.clone(), bytes }) + } + + pub(crate) fn shrink(&mut self, bytes: u64) -> Result<()> { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "completed PNG exceeds its reservation")); + } + self.budget.used.fetch_sub(self.bytes - bytes, Ordering::AcqRel); + self.bytes = bytes; + Ok(()) + } +} +impl Drop for Reservation { + fn drop(&mut self) { + self.budget.used.fetch_sub(self.bytes, Ordering::AcqRel); + } +} + +/// Retained runtime input capacities survive work/PNG eviction through status handles. +fn retained_request_bytes(request: &ImageRequest) -> Result { + let existing = request.raytrace.as_ref().map_or(Ok(0), |options| options.retained_bytes())?; + existing + .checked_add(request.raster_lights_retained_bytes()?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request size overflow")) +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod light_union_lease_tests { + use super::super::{DirectionalLightOptions, PunctualLightOptions, RaytraceOptions, led_strip::LedStripOptions}; + use super::*; + fn request() -> Result { + let mut options = RaytraceOptions { + primary_samples: 16, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]), + punctual_lights: Some(vec![ + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None + }; + 8 + ]), + ..Default::default() + }; + let strip = LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 2.0, + }; + for _ in 0..4 { + strip.append_to(&mut options, 64)?; + } + Ok(ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(options), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }) + } + fn scene() -> ProductScene { + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY } + } + #[test] + fn normalized_union_uses_one_pool_and_keeps_record_lease_after_frame_eviction() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = request().unwrap(); + let bytes = retained_request_bytes(&request).unwrap(); + let capacities = request + .raytrace + .as_ref() + .map(|o| { + (o.lights.as_ref().unwrap().capacity(), o.punctual_lights.as_ref().unwrap().capacity(), o.area_lights.as_ref().unwrap().capacity()) + }) + .unwrap(); + let job = host.submit(JobId { session: 1724, serial: 1, generation: 1 }, 1, scene(), request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Synchronize this test's completed worker before asserting final Arc release; + // publication wakes waiters just before Running drops its temporary handle. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let retained = job.0.request.raytrace.as_ref().unwrap(); + assert_eq!( + capacities, + ( + retained.lights.as_ref().unwrap().capacity(), + retained.punctual_lights.as_ref().unwrap().capacity(), + retained.area_lights.as_ref().unwrap().capacity() + ) + ); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert!(host.admitted_bytes() > bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn failed_union_metadata_reservation_releases_work_and_does_not_enqueue() { + let host = CpuHost::for_platform().unwrap(); + let request = request().unwrap(); + let work = admit(&scene(), &request).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let result = host.submit(JobId { session: 1724, serial: 2, generation: 1 }, 1, scene(), request); + assert_eq!(result.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } + + fn raster_local_pair() -> (ImageRequest, ProductScene) { + let mut input = request().unwrap(); + input.integrator = Integrator::Raster; + input.raytrace = None; + let mut points = Vec::with_capacity(8); + points.push(PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }); + let mut areas = Vec::with_capacity(4); + areas.push(super::super::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }); + input.raster_punctual_lights = Some(points); + input.raster_area_lights = Some(areas); + let mesh = solidcraft_geom::Mesh { + positions: vec![ + solidcraft_geom::Vec3::new(-2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(0.0, 2.0, 0.0), + ], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + name: "Raster local lease fixture".into(), + mesh: Arc::new(mesh), + color: [160; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + bounds, + }; + (input, scene) + } + + #[test] + fn raster_local_record_keeps_original_capacity_lease_after_real_completion_and_frame_drop() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let (input, scene) = raster_local_pair(); + let capacities = (input.raster_punctual_lights.as_ref().unwrap().capacity(), input.raster_area_lights.as_ref().unwrap().capacity()); + let bytes = (capacities.0 * std::mem::size_of::() + + capacities.1 * std::mem::size_of::()) as u64; + assert_eq!(retained_request_bytes(&input).unwrap(), bytes); + let job = host.submit(JobId { session: 1725, serial: 1, generation: 1 }, 1, scene, input).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + assert_eq!(job.0.request.raster_punctual_lights.as_ref().unwrap().capacity(), capacities.0); + assert_eq!(job.0.request.raster_area_lights.as_ref().unwrap().capacity(), capacities.1); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let copied = job.status().unwrap().request; + assert_eq!(copied.raster_punctual_lights, job.0.request.raster_punctual_lights); + assert_eq!(copied.raster_area_lights, job.0.request.raster_area_lights); + drop(copied); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + + #[test] + fn raster_local_metadata_reservation_failure_releases_work_without_enqueuing() { + let host = CpuHost::for_platform().unwrap(); + let (input, scene) = raster_local_pair(); + let work = host.admit(&scene, &input, JobOptions::default()).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let failed = host.submit(JobId { session: 1725, serial: 2, generation: 1 }, 1, scene, input); + assert_eq!(failed.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } +} + +fn admit_request_sum(work_bytes: u64, request_bytes: u64) -> Result<()> { + if work_bytes.checked_add(request_bytes).is_none_or(|sum| sum > super::image::MAX_JOB_BYTES) { + return Err(JobError::new(ErrorCode::LimitExceeded, "render work and retained request exceed 384 MiB per-job admission")); + } + Ok(()) +} + +/// Borrow encoded bytes through the frame, so retaining the data also retains its admission lease. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearColourEncoding { + SceneLinearSrgbD65, +} +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearAlphaConvention { + CoveragePremultiplied, +} +#[derive(Clone, Debug, Serialize)] +pub struct LinearMasterInfo { + pub encoding: LinearColourEncoding, + pub alpha: LinearAlphaConvention, + pub bytes: u64, + pub sha256: String, +} +struct RetainedPresentation { + info: super::presentation::MasterPresentation, + _reservation: Reservation, +} + +pub struct RenderFrame { + // Derivatives point directly at the original, never form a retention chain. + source_master: Option>, + presentation: Option>, + pub info: FrameInfo, + png: Vec, + exr: Option<(Vec, LinearMasterInfo)>, + _reservation: Reservation, +} +impl RenderFrame { + pub fn master_source(self: &Arc) -> Result> { + if let Some(source) = &self.source_master { + return Ok(source.clone()); + } + if self.exr.is_some() { + return Ok(self.clone()); + } + Err(JobError::new(ErrorCode::InvalidRequest, "completed image has no retained raw linear master")) + } + pub fn presentation(&self) -> Option<&super::presentation::MasterPresentation> { + self.presentation.as_deref().map(|retained| &retained.info) + } + pub fn linear_exr(&self) -> Option<&[u8]> { + self.exr.as_ref().map(|(bytes, _)| bytes.as_slice()).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_exr())) + } + pub fn linear_master_info(&self) -> Option<&LinearMasterInfo> { + self.exr.as_ref().map(|(_, info)| info).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_master_info())) + } + pub fn png(&self) -> &[u8] { + &self.png + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct PreviewInfo { + pub frame_sequence: u32, + pub samples_per_pixel: u32, + pub frame: FrameInfo, +} + +/// Immutable checkpoint bytes retain their own transferred host lease. Keeping +/// an older preview alive never makes its memory disappear from pool accounting. +pub struct RenderPreview { + pub info: PreviewInfo, + png: Vec, + _reservation: CheckpointLease, +} + +/// Two reusable, immutable complete-pass slots. No consumer acknowledgement or +/// queue: externally pinned slots are diagnosed and never stall final work. +struct CheckpointCredits { + state: Mutex, + slot_bytes: u64, + capacity: u64, +} +struct CheckpointCreditState { + free: Reservation, + closed: bool, +} +impl CheckpointCredits { + fn new(reservation: &mut Reservation, slot_bytes: u64, slots: u32) -> Result> { + if !(1..=2).contains(&slots) || slot_bytes == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint credits require one or two finite slots")); + } + let capacity = slot_bytes + .checked_mul(u64::from(slots)) + .and_then(|n| n.checked_add(1024)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit capacity overflow"))?; + let free = reservation.split(capacity)?; + Ok(Arc::new(Self { state: Mutex::new(CheckpointCreditState { free, closed: false }), slot_bytes, capacity })) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "checkpoint credit lock poisoned"))?; + if state.closed { + return Err(JobError::new(ErrorCode::Cancelled, "checkpoint credits are closed")); + } + let needed = self.slot_bytes.checked_add(1024).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit bound overflow"))?; + if state.free.bytes < needed { + return Ok(None); + } + let reservation = state.free.split(self.slot_bytes)?; + Ok(Some(CheckpointLease { reservation, credits: self.clone() })) + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + let _ = state.free.shrink(0); + } +} +struct CheckpointLease { + reservation: Reservation, + credits: Arc, +} +impl std::ops::Deref for CheckpointLease { + type Target = Reservation; + fn deref(&self) -> &Reservation { + &self.reservation + } +} +impl Drop for CheckpointLease { + fn drop(&mut self) { + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if !state.closed { + if state.free.bytes.checked_add(self.reservation.bytes).is_some_and(|n| n <= self.credits.capacity) + && state.free.merge_from(&mut self.reservation).is_ok() + { + return; + } + state.closed = true; + let _ = state.free.shrink(0); + } + } +} + +impl RenderPreview { + pub fn png(&self) -> &[u8] { + &self.png + } +} + +/// Metadata for either runtime environment contract; wire objects retain their original shape. +#[derive(Clone, Debug, Serialize)] +#[serde(untagged)] +pub enum JobEnvironmentInfo { + Cpu(crate::lighting::environment_input::EnvironmentInfo), + Gpu(crate::lighting::environment::EnvironmentInfo), +} + +#[derive(Clone, Debug, Serialize)] +pub struct JobStatus { + /// Completed CPU passes whose immutable snapshot could not be published + /// because both admitted slots remained pinned by external consumers. + pub cpu_preview_retention_skips: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub punctual_diagnostics: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub presentation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sampling: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub linear_master: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + pub textures: Option, + pub options: JobOptions, + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, + pub job: JobId, + pub scene_generation: u64, + pub request: ImageRequest, + pub resolved: crate::ResolvedRequest, + pub progress: Progress, + pub error: Option, + pub frame: Option, +} + +struct Data { + cpu_preview_retention_skips: u32, + partial_preview: Option>, + punctual_diagnostics: Option, + sampling: Option, + progress: Progress, + error: Option, + frame: Option>, + preview: Option>, +} +struct Record { + partial: Option>, + presentation: Option>, + textures: Option, + options: JobOptions, + environment: Option, + id: JobId, + scene_generation: u64, + request: ImageRequest, + // Rust fields drop in declaration order: payload before its retained credits. + _request_reservation: Option, + resolved: crate::ResolvedRequest, + cancel: CancelToken, + data: Mutex, + #[cfg(not(target_arch = "wasm32"))] + done: Condvar, +} + +impl Record { + fn notify(&self) { + #[cfg(not(target_arch = "wasm32"))] + self.done.notify_all(); + } +} + +#[derive(Clone)] +pub struct JobHandle(Arc); + +impl JobHandle { + /// Internal admitted-work identity. Equal public IDs need not be one record. + pub(super) fn same_record(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + pub fn id(&self) -> JobId { + self.0.id + } + pub fn status(&self) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + Ok(JobStatus { + cpu_preview_retention_skips: data.cpu_preview_retention_skips, + punctual_diagnostics: data.punctual_diagnostics, + presentation: self.0.presentation.as_deref().map(|retained| retained.info.clone()), + sampling: data.sampling.clone(), + linear_master: data.frame.as_ref().and_then(|frame| frame.linear_master_info().cloned()), + preview: data.preview.as_ref().map(|preview| preview.info.clone()), + textures: self.0.textures.clone(), + options: self.0.options, + environment: self.0.environment.clone(), + job: self.0.id, + scene_generation: self.0.scene_generation, + request: self.0.request.try_clone_for_host()?, + resolved: self.0.resolved.clone(), + progress: data.progress, + error: data.error.clone(), + frame: data.frame.as_ref().map(|f| f.info.clone()), + }) + } + pub fn cancel(&self) -> Result { + if let Some(credits) = &self.0.partial { + credits.close(); + } + let mut released_partial = None; + { + let mut data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + if !data.progress.phase.terminal() { + self.0.cancel.cancel(); + released_partial = data.partial_preview.take(); + data.preview = None; + data.progress.phase = if data.progress.phase == Phase::Queued { Phase::Cancelled } else { Phase::Cancelling }; + } + } + drop(released_partial); + self.0.notify(); + self.status() + } + + /// Native application helper; engine status commands remain non-blocking. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, timeout: std::time::Duration) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + let (data, timed) = self + .0 + .done + .wait_timeout_while(data, timeout, |d| !d.progress.phase.terminal()) + .map_err(|_| JobError::new(ErrorCode::Internal, "render completion lock poisoned"))?; + if timed.timed_out() && !data.progress.phase.terminal() { + return Err(JobError::new(ErrorCode::TimedOut, "render wait timed out")); + } + drop(data); + self.status() + } + pub fn frame(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render result lock poisoned"))?; + let frame = data.frame.clone(); + if frame.as_ref().is_some_and(|f| f.info.job != self.0.id || f.info.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render frame identity does not match its job")); + } + Ok(frame) + } + + /// A provisional complete-pass image, never the final/export frame slot. + pub fn preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview lock poisoned"))?; + let preview = data.preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render preview identity does not match its job")); + } + Ok(preview) + } +} + +#[derive(Clone, Copy)] +enum CpuPreviewPolicy { + Shared(super::PartialPreviewPlan), + Protected(super::ProtectedPreviewPlan), +} +impl CpuPreviewPolicy { + fn preview_plan(self) -> super::PartialPreviewPlan { + match self { + Self::Shared(plan) => plan, + Self::Protected(plan) => plan.preview_plan(), + } + } +} +struct Submission { + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, +} +struct Work { + regrade: Option<(Arc, super::presentation::Presentation)>, + request: Option, + executor: Option>, + environment: Option, + scene: ProductScene, + handle: JobHandle, + reservation: Reservation, +} +// One host advance hashes at most four 16 KiB chunks, independently of the +// integrator's quantum. The unchanged work reservation covers the sole PNG and +// this fixed state until publication; it is not another image task or pool. +const PNG_HASH_CHUNK_BYTES: usize = 16_384; +const PNG_HASH_CHUNKS_PER_ADVANCE: usize = 4; +pub(crate) const FRAME_METADATA_BYTES: u64 = 1024; + +struct PendingPng { + png: Vec, + digest: Sha256, + hashed: usize, + preview_samples: Option, + exr: Option>, + png_digest: Option>, + exr_hashed: usize, +} +// Keep the new fixed completion state within the existing metadata allowance +// even if the hashing dependency's representation changes on another target. +const _: [(); 1] = [(); (std::mem::size_of::() <= 512) as usize]; +const _: [(); 1] = [(); (std::mem::size_of::() + + std::mem::size_of::() + + std::mem::size_of::() + + 64 + + 2 * crate::MAX_RENDER_ID_BYTES + + 32 + <= FRAME_METADATA_BYTES as usize) as usize]; + +impl PendingPng { + fn new(png: Vec) -> Self { + Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, png_digest: None, exr_hashed: 0 } + } + + #[cfg(feature = "raytrace-cpu")] + fn preview(png: Vec, samples: u32) -> Self { + 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 { + cancel.check()?; + self.finish_png_digest(); + for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) { + 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) + } else { + break; + }; + let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len()); + 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())) + } + fn progress(&self) -> Progress { + Progress { + phase: Phase::Encoding, + done: self.hashed as u64 + self.exr_hashed as u64, + total: self.png.len() as u64 + self.exr.as_ref().map_or(0, |bytes| bytes.len() as u64), + } + } +} + +#[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 = (0..quantum_bytes + 13).map(|index| (index as u8).wrapping_mul(17).wrapping_add(3)).collect(); + let exr: Option> = 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>, + task: Option, + pending_png: Option, + handle: JobHandle, + reservation: Option, + next_preview_sequence: u32, + next_checkpoint_pass: u32, + checkpoints: Option>, + // Task/PNG allocations above die before the in-flight credit below. + partial: Option>, +} + +impl Drop for Running { + fn drop(&mut self) { + if let Some(credits) = &self.checkpoints { + credits.close(); + } + } +} + +/// One fallibly allocated task, keeping the dispatch enum small in either build. +/// Its bounded metadata allocation fits the existing per-job task allowance. +struct TaskSlot(Vec); +impl TaskSlot { + fn new(task: T) -> Result { + if std::mem::size_of::() > 4096 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task metadata exceeds its admission allowance")); + } + let mut tasks = Vec::new(); + tasks.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve render task slot"))?; + if tasks.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task slot exceeds its bounded capacity")); + } + tasks.push(task); + Ok(Self(tasks)) + } + fn get_mut(&mut self) -> Result<&mut T> { + self.0.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task slot")) + } +} +enum WorkTask { + Regrade(TaskSlot), + Registered(Box), + Raster(TaskSlot), + #[cfg(feature = "raytrace-cpu")] + Raytrace(TaskSlot), +} + +enum WorkPoll { + #[cfg(feature = "raytrace-cpu")] + Partial { + png: Vec, + covered: Vec, + completed_passes: u32, + updated_prefix: u64, + }, + Existing(TaskPoll), + #[cfg(feature = "raytrace-cpu")] + Preview { + png: Vec, + samples_per_pixel: u32, + }, +} + +impl WorkTask { + fn protected_report(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.protected_preview_report()), + _ => None, + } + } + fn partial_ready(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.get_mut()?.partial_preview_ready(plan), + _ => Ok(false), + } + } + fn completed_pass_ready(&self, plan: super::PartialPreviewPlan) -> Result> { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().map_or(Ok(None), |task| task.completed_pass_preview_ready(plan)), + _ => Ok(None), + } + } + fn begin_partial(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => match task.get_mut()?.begin_partial_preview(plan)? { + crate::raytrace::image::PartialBegin::Started => Ok(true), + crate::raytrace::image::PartialBegin::Exhausted => Ok(false), + }, + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn step_partial(&mut self, units: usize) -> Result { + let _ = &units; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_partial_previews(units)? { + crate::raytrace::image::PartialImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::PartialImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix } => { + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } + } + }), + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn punctual_diagnostics(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.punctual_diagnostics()), + _ => None, + } + } + + fn source_master(&self) -> Result>> { + match self { + Self::Regrade(slot) => { + slot.0.first().map(|task| Some(task.source())).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing master task slot")) + } + _ => Ok(None), + } + } + fn sampling_report(&self) -> Option { + match self { + Self::Registered(task) => task.sampling_report(), + _ => None, + } + } + fn take_linear_exr(&mut self) -> Option> { + match self { + Self::Registered(task) => task.take_linear_exr(), + _ => None, + } + } + fn new( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + environment: Option, + job_options: JobOptions, + partial: Option, + report_sink: Option<&PartialCredits>, + ) -> Result { + let _ = (&environment, &job_options, &partial, &report_sink); + match request.integrator { + Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster), + Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let options = request.raytrace.clone().unwrap_or_default(); + let task = match partial { + Some(CpuPreviewPolicy::Shared(plan)) => crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ), + Some(CpuPreviewPolicy::Protected(plan)) => { + crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ) + } + None => crate::raytrace::image::ImageTask::new_with_environment_and_nested( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + ), + }; + Self::raytrace_with_slot(task?, report_sink, TaskSlot::new) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + } + + fn step(&mut self, units: usize) -> Result { + match self { + Self::Regrade(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + Self::Registered(task) => task.step(units).map(WorkPoll::Existing), + Self::Raster(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_previews(units)? { + crate::raytrace::image::ImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::ImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::ImagePoll::Preview { png, samples_per_pixel } => WorkPoll::Preview { png, samples_per_pixel }, + }), + } + } +} + +fn terminal(handle: &JobHandle, error: JobError) { + if let Some(credits) = &handle.0.partial { + credits.close(); + } + let mut released_partial = None; + if let Ok(mut data) = handle.0.data.lock() { + if data.progress.phase == Phase::Completed { + return; + } + if handle.0.cancel.is_cancelled() || error.code == ErrorCode::Cancelled { + data.progress.phase = Phase::Cancelled; + data.error = None; + } else { + data.progress.phase = Phase::Failed; + data.error = Some(error); + } + data.frame = None; + data.preview = None; + released_partial = data.partial_preview.take(); + } + drop(released_partial); + handle.0.notify(); +} + +impl Running { + fn begin(work: Work) -> Option { + Self::begin_with_partial_factory(work, |credits| TaskSlot::new(PartialRunning::new(credits))) + } + + // The private factory keeps post-construction setup fallible without losing + // the real ledger. It runs only after report capture and outside every lock. + fn begin_with_partial_factory( + mut work: Work, + make_partial: impl FnOnce(Arc) -> Result>, + ) -> Option { + let checkpoints = (|| { + let slots = work + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .filter(|_| work.handle.0.partial.is_none() && work.executor.is_none()) + .map_or(0, |options| options.samples_per_pixel.saturating_sub(1).min(2)); + if slots == 0 { + return Ok(None); + } + let slot_bytes = u64::from(work.handle.0.request.width) + .checked_mul(u64::from(work.handle.0.request.height)) + .and_then(|n| n.checked_mul(8)) + .and_then(|n| n.checked_add(65_536 + FRAME_METADATA_BYTES)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint slot overflow"))?; + CheckpointCredits::new(&mut work.reservation, slot_bytes, slots).map(Some) + })(); + let checkpoints = match checkpoints { + Ok(credits) => credits, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + if work.handle.0.cancel.is_cancelled() { + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render cancelled")); + return None; + } + if let Ok(mut data) = work.handle.0.data.lock() + && !work.handle.0.cancel.is_cancelled() + { + data.progress.phase = Phase::Preparing; + } + let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if let Some((source, presentation)) = work.regrade { + super::regrade::RegradeTask::new(source, presentation, work.handle.0.cancel.clone()).and_then(TaskSlot::new).map(WorkTask::Regrade) + } else if let Some(executor) = work.executor { + let request = work.request.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing registered executor request"))?; + executor.begin(work.scene, request, work.handle.0.options, work.handle.0.cancel.clone()).map(WorkTask::Registered) + } else { + WorkTask::new( + work.scene, + work.handle.0.request.try_clone_for_host()?, + work.handle.0.cancel.clone(), + work.environment, + work.handle.0.options, + work.handle.0.partial.as_ref().map(|credits| credits.policy()), + work.handle.0.partial.as_deref(), + ) + } + })) + .unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job"))); + let task = match task { + Ok(task) => task, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + // The raw producer report was captured before the first task-slot wrap. + // Only now attempt the additional partial runtime slot. + let partial = work.handle.0.partial.as_ref().map(|credits| make_partial(credits.clone())).transpose(); + match partial { + Ok(partial) => Some(Self { + partial, + source_master: None, + task: Some(task), + pending_png: None, + handle: work.handle, + reservation: Some(work.reservation), + next_preview_sequence: 1, + next_checkpoint_pass: 1, + checkpoints, + }), + Err(error) => { + terminal(&work.handle, error); + // The real task's buffers die before work's remaining lease. + None + } + } + } + fn advance(&mut self, units: usize) -> Result { + self.handle.0.cancel.check()?; + if self.pending_png.is_some() { + return self.advance_png(units); + } + if let Some(partial) = self.partial.as_mut() { + let partial = partial.get_mut()?; + let task = self.task.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + let uniform_pass = if self.handle.0.request.cpu_progressive_every_pass { task.completed_pass_ready(partial.credits.plan)? } else { None }; + let automatic_pass = uniform_pass.filter(|pass| *pass > partial.last_pass_attempt); + if let Some(pass) = automatic_pass { + partial.last_pass_attempt = pass; + partial.credits.request()?; + } + if partial.lease.is_none() + && partial.credits.requested.load(Ordering::Acquire) + && !partial.credits.exhausted.load(Ordering::Acquire) + && (uniform_pass.is_none() || automatic_pass.is_some()) + { + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + if task.partial_ready(partial.credits.plan)? { + let mut lease = partial.credits.acquire()?; + if lease.is_none() && automatic_pass.is_some() { + let released = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retirement lock poisoned"))? + .partial_preview + .take(); + drop(released); + lease = partial.credits.acquire()?; + } + if lease.is_none() && automatic_pass.is_some() && partial.credits.retained_slots_blocked()? { + let mut data = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retention diagnostic lock poisoned"))?; + self.handle.0.cancel.check()?; + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retention diagnostic overflow"))?; + } + if let Some(lease) = lease { + // Keep the lease past any producer error until task buffers drop. + partial.lease = Some(lease); + let begin = task.begin_partial(partial.credits.plan); + partial.credits.store_report(task.protected_report())?; + if !begin? { + if partial.credits.protected.is_some() && !partial.credits.exhausted.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::Internal, "protected feedback refused without real quota exhaustion")); + } + partial.credits.exhaust(); + drop(partial.lease.take()); + } + } + } + } + } + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task"))?; + let result = if self.partial.is_some() { task.step_partial(units) } else { task.step(units) }; + if let Some(credits) = &self.handle.0.partial { + credits.store_report(task.protected_report())?; + } + let result = result?; + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + data.punctual_diagnostics = self.task.as_ref().and_then(WorkTask::punctual_diagnostics); + // The final publication check is under the same lock as cancellation. + if self.handle.0.cancel.is_cancelled() { + data.progress.phase = Phase::Cancelled; + data.frame = None; + data.preview = None; + let released = data.partial_preview.take(); + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + return Ok(false); + } + match result { + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } => { + drop(data); + self.capture_partial(png, covered, completed_passes, updated_prefix)?; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Pending(progress)) => { + data.progress = progress; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Complete(png)) => { + // Drop every integrator-owned capture/scratch buffer first, but + // keep the original admission lease while hashing the sole PNG. + self.source_master = self.task.as_ref().map(WorkTask::source_master).transpose()?.flatten(); + data.sampling = self.task.as_ref().and_then(WorkTask::sampling_report); + let exr = self.task.as_mut().and_then(WorkTask::take_linear_exr); + if exr.is_some() != self.handle.0.options.linear_exr { + return Err(JobError::new(ErrorCode::Internal, "linear master availability differs from the admitted request")); + } + if let Some(bytes) = &exr { + let limit = super::linear_exr::encoded_limit(self.handle.0.request.width, self.handle.0.request.height)?; + if bytes.len() < 8 || bytes.capacity() as u64 > limit || bytes.get(..8) != Some(&[0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]) { + return Err(JobError::new(ErrorCode::LimitExceeded, "linear master exceeds its bound or has an invalid signature")); + } + } + self.task = None; + let mut pending = PendingPng::new(png); + pending.exr = exr; + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Preview { png, samples_per_pixel } => { + // Retain the integrator/film and the entire remaining work lease. + // Hash the checkpoint before making immutable bytes observable. + let pending = PendingPng::preview(png, samples_per_pixel); + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + } + } + + fn advance_png(&mut self, units: usize) -> Result { + // No status/data lock is held while scanning the encoded image. + let pending = self.pending_png.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing pending PNG"))?; + if !pending.step(units, &self.handle.0.cancel)? { + let progress = pending.progress(); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + self.handle.0.cancel.check()?; + data.progress = progress; + return Ok(true); + } + 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, png_digest); + } + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: self.handle.0.request.width, + height: self.handle.0.request.height, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + 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. + // The PNG allocation itself is retained once and billed by capacity below. + let frame_layout = if preview_samples.is_some() { std::mem::size_of::() } else { std::mem::size_of::() }; + let checkpoint_metadata = + if preview_samples.is_some() { std::mem::size_of::() + 2 * std::mem::size_of::() } else { 0 }; + let fixed_metadata = std::mem::size_of::() + frame_layout + checkpoint_metadata + 2 * crate::MAX_RENDER_ID_BYTES + 32; + let linear_digest_bytes = if exr.is_some() { 64 } else { 0 }; + if fixed_metadata + .checked_add(info.png_sha256.capacity()) + .and_then(|n| n.checked_add(linear_digest_bytes)) + .is_none_or(|bytes| bytes > FRAME_METADATA_BYTES as usize) + { + return Err(JobError::new(ErrorCode::LimitExceeded, "PNG digest metadata exceeds its existing admission allowance")); + } + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + // Cancellation shares this lock; a late cancel must win before frame + // installation. The digest is complete; checkpoints retain task scratch, + // while the final-only path has already released it. + self.handle.0.cancel.check()?; + if let Some(samples_per_pixel) = preview_samples { + let options = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "preview requires CPU progressive intent"))?; + let frame_sequence = self.next_preview_sequence; + let expected = Some(self.next_checkpoint_pass); + if expected != Some(samples_per_pixel) || samples_per_pixel >= options.samples_per_pixel || self.task.is_none() { + return Err(JobError::new(ErrorCode::Internal, "invalid progressive checkpoint sequence")); + } + let next_sequence = frame_sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::Internal, "preview sequence exhausted"))?; + let credits = self.checkpoints.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing checkpoint credits"))?; + if (png.capacity() as u64).checked_add(FRAME_METADATA_BYTES).is_none_or(|bytes| bytes > credits.slot_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "checkpoint PNG exceeds its admitted slot")); + } + let mut reservation = credits.acquire()?; + if reservation.is_none() { + // Retire the host's obsolete slot before treating a consumer as + // pinned. A headless client never has to acknowledge previews. + let released = data.preview.take(); + drop(data); + drop(released); + reservation = credits.acquire()?; + data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; + self.handle.0.cancel.check()?; + } + self.next_checkpoint_pass = if self.handle.0.request.cpu_progressive_every_pass { + self.next_checkpoint_pass.checked_add(1) + } else { + self.next_checkpoint_pass.checked_mul(2) + } + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; + let Some(reservation) = reservation else { + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint retention diagnostic overflow"))?; + return Ok(true); + }; + data.preview = Some(Arc::new(RenderPreview { + info: PreviewInfo { frame_sequence, samples_per_pixel, frame: info }, + png, + _reservation: reservation, + })); + self.next_preview_sequence = next_sequence; + let pixels = u64::from(self.handle.0.request.width) * u64::from(self.handle.0.request.height); + data.progress = + Progress { phase: Phase::Running, done: pixels * u64::from(samples_per_pixel), total: pixels * u64::from(options.samples_per_pixel) }; + self.handle.0.notify(); + return Ok(true); + } + let exr = exr.map(|bytes| { + let info = LinearMasterInfo { + bytes: bytes.len() as u64, + sha256: format!("{:x}", digest.finalize()), + encoding: LinearColourEncoding::SceneLinearSrgbD65, + alpha: LinearAlphaConvention::CoveragePremultiplied, + }; + (bytes, info) + }); + let retained = png.capacity() as u64 + exr.as_ref().map_or(0, |(bytes, _)| bytes.capacity() as u64) + FRAME_METADATA_BYTES; + let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?; + reservation.shrink(retained)?; + data.frame = Some(Arc::new(RenderFrame { + info, + png, + exr, + source_master: self.source_master.take(), + presentation: self.handle.0.presentation.clone(), + _reservation: reservation, + })); + data.preview = None; + let released = data.partial_preview.take(); + data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + if let Some(credits) = &self.checkpoints { + credits.close(); + } + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + Ok(false) + } + + fn guarded_step(&mut self, units: usize) -> bool { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.advance(units))); + match result { + Ok(Ok(more)) => more, + Ok(Err(e)) => { + terminal(&self.handle, e); + false + } + Err(_) => { + terminal(&self.handle, JobError::new(ErrorCode::Internal, "image host encountered an internal error")); + false + } + } + } +} + +struct Shared { + queue: Mutex>, + active: Mutex>>, + stop: AtomicBool, + budget: Arc, + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar, +} + +struct Owner { + executor: Option>, + shared: Arc, + kind: HostKind, + running: Mutex>, + #[cfg(not(target_arch = "wasm32"))] + _worker: Option>, +} + +impl Drop for Owner { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Release); + if let Ok(active) = self.shared.active.lock() + && let Some(record) = active.as_ref().and_then(Weak::upgrade) + { + let _ = JobHandle(record).cancel(); + } + if let Ok(mut queue) = self.shared.queue.lock() { + for work in queue.iter() { + let _ = work.handle.cancel(); + } + queue.clear(); + } + if let Ok(mut running) = self.running.lock() + && let Some(work) = running.take() + { + let _ = work.handle.cancel(); + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render host closed")); + } + #[cfg(not(target_arch = "wasm32"))] + self.shared.wake.notify_all(); + // Detaching cannot stall the UI; the bounded worker observes stop/cancel at its next unit. + } +} + +#[derive(Clone)] +pub struct ImageHost(Arc); + +/// Builtin CPU constructors share the registered image host lifetime machinery. +pub type CpuHost = ImageHost; + +impl ImageHost { + fn shared(limit: u64) -> Arc { + Arc::new(Shared { + queue: Mutex::new(VecDeque::new()), + active: Mutex::new(None), + stop: AtomicBool::new(false), + budget: Arc::new(Budget { used: AtomicU64::new(0), limit }), + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar::new(), + }) + } + + pub fn cooperative() -> Self { + Self(Arc::new(Owner { + executor: None, + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + /// A cooperative host over `executor` (pumped by its caller). + #[cfg(test)] + fn cooperative_with(executor: Arc) -> Self { + Self(Arc::new(Owner { + executor: Some(executor), + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + pub fn for_platform() -> Result { + #[cfg(target_arch = "wasm32")] + { + Ok(Self::cooperative()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let pool = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + let shared = Self::shared(pool); + let worker_shared = shared.clone(); + let worker = std::thread::Builder::new() + .name("solidcraft-render".into()) + .spawn(move || native_worker(worker_shared)) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, format!("could not start CPU image worker: {e}")))?; + Ok(Self(Arc::new(Owner { executor: None, shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + } + + /// Start an isolated bounded native worker. GPU discovery occurs before registration. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_executor(executor: Arc) -> Result { + let descriptor = executor.descriptor()?; + if descriptor.profiles.len() != 1 + || descriptor + .profiles + .iter() + .any(|p| p.mode != RenderMode::Preview || p.operation != RenderOperation::Image || p.formats != [RenderFormat::Png]) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "image worker currently accepts one Preview/Image/PNG profile")); + } + let limit = executor.memory_limit_bytes(); + let ceiling = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + if limit == 0 || limit > ceiling { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image pool exceeds supported address space")); + } + let shared = Self::shared(limit); + let worker_shared = shared.clone(); + let worker = std::thread::Builder::new() + .name("solidcraft-render".into()) + .spawn(move || native_worker(worker_shared)) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, format!("could not start image worker: {e}")))?; + Ok(Self(Arc::new(Owner { executor: Some(executor), shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + + pub fn kind(&self) -> HostKind { + self.0.kind + } + + pub fn same_host(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub fn is_available(&self) -> bool { + !self.0.shared.stop.load(Ordering::Acquire) + } + pub fn admitted_bytes(&self) -> u64 { + self.0.shared.budget.used.load(Ordering::Acquire) + } + + /// Internal completed-film adapter: the existing host budget, no new pool. + pub(crate) fn reserve_film_snapshot(&self, bytes: u64) -> Result { + if self.0.executor.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU film snapshots require the builtin CPU host")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped")); + } + if bytes > super::image::MAX_JOB_BYTES { + return Err(JobError::new(ErrorCode::LimitExceeded, "film snapshot exceeds per-job admission")); + } + self.0.shared.budget.reserve(bytes) + } + + pub fn descriptor(&self) -> Result { + self.descriptor_for(Integrator::Raster) + } + + pub fn job_limit_bytes(&self) -> u64 { + if self.0.executor.is_some() { self.0.shared.budget.limit } else { super::image::MAX_JOB_BYTES } + } + + pub fn pool_limit_bytes(&self) -> u64 { + self.0.shared.budget.limit + } + + pub fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + self.admit_with_policy(scene, request, options, None) + } + /// Same canonical policy and complete retained/HDR accounting as protected submit. + /// Non-reserving estimate: submission still admits against the live pool. + pub fn admit_cpu_protected_partial_with_environment_and_options( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result { + self.validate_submission_environment(scene, request, environment)?; + let policy = Self::protected_preview_policy(request)?; + let (mut admission, request_bytes) = self.admit_submission(scene, request, options, environment, Some(policy))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(request_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request admission overflow"))?; + Ok(admission) + } + + fn protected_preview_policy(request: &ImageRequest) -> Result { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require CPU progressive intent"))? + .samples_per_pixel; + let plan = super::ProtectedPreviewPlan::with_cadence(request.width, request.height, samples, request.cpu_budget(), request.cpu_progressive_every_pass)?; + Ok(CpuPreviewPolicy::Protected(plan)) + } + + fn validate_submission_environment( + &self, + scene: &ProductScene, + request: &ImageRequest, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result<()> { + if self.0.executor.is_some() && environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU environments")); + } + if environment.is_some() && request.integrator != Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "environment lighting requires CPU raytrace")); + } + self.validate_integrator(request.integrator)?; + if environment.is_some() { + request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(scene)?; + } + Ok(()) + } + + fn admit_submission( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + partial: Option, + ) -> Result<(Admission, u64)> { + if environment.is_some() && request.raytrace.as_ref().is_some_and(|options| options.directional_shadow_transmission) { + return Err(JobError::new(ErrorCode::InvalidRequest, "directional shadow transmission does not support HDR environments")); + } + let metadata_bytes = + (if environment.is_some() { std::mem::size_of::() as u64 } else { 0 }) + + request.retained_resource_metadata_bytes(); + let request_bytes = retained_request_bytes(request)? + .checked_add(metadata_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?; + let mut admission = self.admit_with_policy(scene, request, options, partial)?; + let environment_bytes = + environment.map_or(Ok(0), |value| value.required_bytes()).map_err(|error| JobError::new(ErrorCode::InvalidRequest, error.to_string()))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + admission.preparation_bytes = admission + .preparation_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + self.check_request_sum(admission.estimated_total_bytes, request_bytes, request.cpu_budget())?; + Ok((admission, request_bytes)) + } + + fn admit_with_policy( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + partial: Option, + ) -> Result { + request.validate_raster_request()?; + if self.0.executor.is_some() && (request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0) { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept Raster-only lights or exposure")); + } + if let Some(policy) = partial { + let plan = policy.preview_plan(); + if self.0.executor.is_some() + || request.integrator != Integrator::Raytrace + || request.transparent_background + || request.environment.is_some() + || request.textures.is_some() + || request.raytrace.as_ref().and_then(|v| v.progressive).is_none() + || plan != super::PartialPreviewPlan::new(request.width, request.height)? + { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial previews require the canonical builtin CPU progressive request")); + } + if let CpuPreviewPolicy::Protected(protected) = policy { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require a progressive sample target"))? + .samples_per_pixel; + protected.validate()?; + if protected != super::ProtectedPreviewPlan::with_cadence(request.width, request.height, samples, request.cpu_budget(), request.cpu_progressive_every_pass)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan does not match its admitted request")); + } + } + } + let scatter = |t: Option| t.and_then(|v| v.subsurface()).is_some_and(|s| s.active()); + if scene.meshes.iter().any(|b| scatter(b.transmission) || b.faces.iter().any(|f| scatter(f.transmission))) + && !self.0.executor.as_ref().is_some_and(|executor| executor.supports_subsurface()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "installed image producer does not implement interior subsurface random walks")); + } + + self.validate_integrator(request.integrator)?; + options.validate()?; + if let Some(executor) = &self.0.executor { + if request.raytrace.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept CPU raytrace options")); + } + if options.aging.active() && !executor.supports_aging() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot evaluate ordered surface aging")); + } + if options.finishing.photographic.active() && !executor.supports_photographic() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply photographic lens effects")); + } + if options.nested_media && !executor.supports_nested_media() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement certified nested media")); + } + if options.volume.is_some() && !executor.supports_volume() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement bounded homogeneous volume transport")); + } + if options.adaptive.is_some() && !executor.supports_adaptive_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement independent-pilot adaptive sampling")); + } + if options.transmission_samples != 1 && !executor.supports_transmission_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement transmission strata")); + } + if options.linear_exr && !executor.supports_linear_exr() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot retain a raw linear EXR")); + } + if options.finishing.bloom.is_some_and(|b| b.active()) && !executor.supports_bloom() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement display bloom")); + } + if (!options.finishing.is_identity() || options.backdrop.is_some()) && !executor.supports_finishing() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply the requested finishing/backdrop")); + } + let admission = executor.admit(scene, request, options)?; + if admission.estimated_total_bytes > self.job_limit_bytes() { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(admission) + } else { + request.cpu_budget().validate_execution()?; + // Only the existing nesting opt-in is admitted on the CPU raytrace path. + // Every other JobOptions field retains its exact default-only contract. + if (JobOptions { nested_media: false, ..options }) != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU images use raytrace options, not progressive sampling controls")); + } + if let Some(policy) = partial { + #[cfg(feature = "raytrace-cpu")] + { + let raytrace = request + .raytrace + .as_ref() + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "partial previews require CPU progressive options"))?; + return match policy { + CpuPreviewPolicy::Shared(plan) => { + crate::raytrace::image::admit_with_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + CpuPreviewPolicy::Protected(plan) => { + crate::raytrace::image::admit_with_protected_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + }; + } + #[cfg(not(feature = "raytrace-cpu"))] + { + let _ = policy; + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + } + if !options.nested_media { + return admit(scene, request); + } + if request.integrator != Integrator::Raytrace || request.environment.is_some() || request.textures.is_some() || scene.has_transmission() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU nested media require explicit raytrace dielectric overrides")); + } + #[cfg(feature = "raytrace-cpu")] + { + let defaults = super::RaytraceOptions::default(); + let raytrace = request.raytrace.as_ref().unwrap_or(&defaults); + crate::raytrace::image::admit_with_nested(scene, request, raytrace, true) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + + fn check_request_sum(&self, work: u64, request: u64, budget: super::CpuBudget) -> Result<()> { + if self.0.executor.is_none() { + if budget == super::CpuBudget::Compact { + return admit_request_sum(work, request); + } + if work.checked_add(request).is_none_or(|n| n > budget.limits().max_job_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "CPU work and retained request exceed the selected profile")); + } + return Ok(()); + } + if work.checked_add(request).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(()) + } + + /// Check the execution choice without capturing geometry or reserving memory. + pub fn validate_integrator(&self, integrator: Integrator) -> Result<()> { + if self.0.executor.is_some() && integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing requires the native worker host")); + } + Ok(()) + } + + /// Select exactly one executor for this request. Never rely on registry order + /// to choose between raster and raytracing implementations. + pub fn descriptor_for(&self, integrator: Integrator) -> Result { + if let Some(executor) = &self.0.executor { + if integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + let mut descriptor = executor.descriptor()?; + if !self.is_available() { + descriptor.availability = Availability::Unavailable { reason: "image host has stopped".into() }; + } + return Ok(descriptor); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + Ok(ExecutorDescriptor { + id: ExecutorId::new(match integrator { + Integrator::Raster => "cpu-product", + Integrator::Raytrace => "cpu-raytrace", + }) + .map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: if self.0.shared.stop.load(Ordering::Acquire) { + Availability::Unavailable { reason: "image host has stopped".into() } + } else if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + Availability::Unavailable { reason: "CPU raytracing requires the native worker host".into() } + } else { + Availability::Available + }, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: if integrator == Integrator::Raytrace && cfg!(feature = "raytrace-cpu") && self.kind() == HostKind::NativeWorker { + // Refraction is the certified thin-sheet/axis-aligned-box CPU preview + // contract. Admission still refuses unsupported geometry and combinations. + vec![crate::RenderFeature::Pbr, crate::RenderFeature::Hdri, crate::RenderFeature::Refraction] + } else { + vec![crate::RenderFeature::Pbr] + }, + }], + limits: if integrator == Integrator::Raytrace && self.kind() == HostKind::NativeWorker && usize::BITS >= 64 { + super::CpuBudget::Workstation.image_limits(false) + } else { + RenderLimits::default() + }, + scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }) + } + + /// Resolve a CPU request against its explicit envelope, never the largest advertised one. + pub fn descriptor_for_request(&self, request: &ImageRequest) -> Result { + let mut descriptor = self.descriptor_for(request.integrator)?; + if self.0.executor.is_none() && request.integrator == Integrator::Raytrace { + let budget = request.cpu_budget(); + budget.validate_execution()?; + budget.validate_image(request.width, request.height, request.raytrace.as_ref().and_then(|o| o.progressive))?; + descriptor.limits = budget.image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())); + } + Ok(descriptor) + } + + pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result { + self.submit_with_environment(id, scene_generation, scene, request, None) + } + + /// Captured HDR ownership stays in work, never serialized/cloned into status. + pub fn submit_with_environment( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + environment: Option, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, JobOptions::default(), environment) + } + + pub fn submit_with_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, options, None) + } + + pub fn submit_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, None) + } + /// Transient CPU presentation policy. Final request and legacy observers are unchanged. + pub fn submit_cpu_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let plan = super::PartialPreviewPlan::new(request.width, request.height)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(CpuPreviewPolicy::Shared(plan))) + } + /// Opt-in protected feedback preserves ordinary work while admitting a finite extra quota. + pub fn submit_cpu_protected_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let policy = Self::protected_preview_policy(&request)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(policy)) + } + fn submit_with_policy(&self, input: Submission, partial_plan: Option) -> Result { + let Submission { id, scene_generation, scene, request, options, environment } = input; + self.validate_submission_environment(&scene, &request, environment.as_ref())?; + if id.session == 0 || id.serial == 0 || id.generation == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); + } + let environment_info = environment + .as_ref() + .map(|e| JobEnvironmentInfo::Cpu(e.metadata())) + .or_else(|| request.environment.as_ref().map(|source| JobEnvironmentInfo::Gpu(source.info().clone()))); + let textures = request.textures.as_ref().map(|source| source.summary()); + let mut features = scene.required_features(); + if environment.is_some() || request.environment.is_some() { + features.push(crate::RenderFeature::Hdri); + } + if request.integrator == Integrator::Raytrace + && request.raytrace.as_ref().is_some_and(|options| !options.dielectrics.is_empty()) + && !features.contains(&crate::RenderFeature::Refraction) + { + features.push(crate::RenderFeature::Refraction); + } + let (Admission { estimated_total_bytes, .. }, request_bytes) = + self.admit_submission(&scene, &request, options, environment.as_ref(), partial_plan)?; + let mut backend = crate::builtin_backend(); + let descriptor = self.descriptor_for_request(&request)?; + let expected_executor = descriptor.id.clone(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(request.width), + height: u64::from(request.height), + format: Some(RenderFormat::Png), + features, + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?; + if resolved.executor != expected_executor { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product executor is unavailable")); + } + let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; + if self.0.shared.stop.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + self.check_request_sum(estimated_total_bytes, request_bytes, request.cpu_budget())?; + let mut reservation = self.0.shared.budget.reserve(estimated_total_bytes)?; + + let partial_credits = partial_plan + .map(|policy| match policy { + CpuPreviewPolicy::Shared(plan) => PartialCredits::new(plan, &mut reservation), + CpuPreviewPolicy::Protected(plan) => PartialCredits::new_protected(plan, &mut reservation), + }) + .transpose()?; + let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; + // Preserve the original CPU option capacities in the retained request and its lease. + // Registered executors instead move resource Arcs into work and keep a small public copy. + let (public_request, work_request) = if self.0.executor.is_some() { + (ImageRequest { environment: None, textures: None, ..request.clone() }, Some(request)) + } else { + (request, None) + }; + let handle = JobHandle(Arc::new(Record { + partial: partial_credits, + presentation: None, + textures, + options, + environment: environment_info, + _request_reservation: request_reservation, + id, + scene_generation, + request: public_request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: None, + request: work_request, + executor: self.0.executor.clone(), + scene, + handle: handle.clone(), + reservation, + environment, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Regrade the exact retained native master. No geometry, material, light or + /// device work is submitted. The original frame and its lease remain shared. + pub fn submit_regrade(&self, id: JobId, source: &JobHandle, presentation: super::presentation::Presentation) -> Result { + if id.session == 0 || id.serial == 0 || id.generation == 0 || id.session != source.id().session || id == source.id() { + return Err(JobError::new(ErrorCode::WrongOwner, "regrade requires a new identity in the source document session")); + } + let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; + let master = frame.master_source()?; + let bytes = super::regrade::required_bytes(&master, presentation)?; + let raw = master.linear_master_info().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "raw master metadata is missing"))?; + let origin = super::presentation::MasterPresentation { + source_job: source.id(), + master_job: master.info.job, + master_sha256: raw.sha256.clone(), + presentation, + denoise_applied: false, + }; + let metadata_bytes = (std::mem::size_of::() + origin.master_sha256.capacity() + 32) as u64; + if bytes.checked_add(metadata_bytes).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "master presentation exceeds the installed host's resource budget")); + } + let limits = RenderLimits { max_scratch_bytes: self.job_limit_bytes(), ..super::GPU_PATH_LIMITS }; + let descriptor = ExecutorDescriptor { + id: ExecutorId::new("linear-master").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: Availability::Available, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: Vec::new(), + }], + limits, + scratch: ScratchLayout { sample_scale: 1, sample_bytes_per_pixel: 32, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }; + let mut backend = crate::builtin_backend(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(frame.info.width), + height: u64::from(frame.info.height), + format: Some(RenderFormat::Png), + features: Vec::new(), + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width: frame.info.width, + height: frame.info.height, + camera: source.0.request.camera, + background: presentation.background, + transparent_background: presentation.transparent_background, + environment: None, + textures: None, + integrator: Integrator::Raster, + raytrace: None, + }; + let options = JobOptions { + finishing: presentation.finishing, + backdrop: presentation.backdrop, + exposure_ev: presentation.exposure_ev, + tone_map: presentation.tone_map, + ..Default::default() + }; + let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; + if self.0.shared.stop.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + let reservation = self.0.shared.budget.reserve(bytes)?; + let metadata = self.0.shared.budget.reserve(metadata_bytes)?; + let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); + let handle = JobHandle(Arc::new(Record { + partial: None, + presentation: Some(origin), + textures: None, + options, + environment: None, + _request_reservation: None, + id, + scene_generation: frame.info.scene_generation, + request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: Some((master, presentation)), + request: None, + executor: None, + environment: None, + scene: ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + handle: handle.clone(), + reservation, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Cooperative callers pump a small quantum independently of polling a job's status. + /// Native jobs run even when the UI is idle or a headless caller is not polling. + pub fn pump(&self, units: usize) -> Result { + if self.0.kind != HostKind::Cooperative { + return Ok(false); + } + let mut running = self.0.running.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "cooperative host lock poisoned"))?; + if running.is_none() { + let work = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.pop_front(); + if let Some(work) = work { + *running = Running::begin(work); + } + } + if let Some(work) = running.as_mut() { + if let Ok(mut active) = self.0.shared.active.lock() { + *active = Some(Arc::downgrade(&work.handle.0)); + } + if !work.guarded_step(units) { + *running = None; + if let Ok(mut active) = self.0.shared.active.lock() { + *active = None; + } + } + } + Ok(running.is_some() + || !self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.is_empty()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_worker(shared: Arc) { + loop { + let mut queue = match shared.queue.lock() { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + while queue.is_empty() && !shared.stop.load(Ordering::Acquire) { + queue = match shared.wake.wait(queue) { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + } + if shared.stop.load(Ordering::Acquire) { + return; + } + let work = queue.pop_front(); + drop(queue); + let Some(mut running) = work.and_then(Running::begin) else { continue }; + if let Ok(mut active) = shared.active.lock() { + *active = Some(Arc::downgrade(&running.handle.0)); + } + loop { + if shared.stop.load(Ordering::Acquire) { + let _ = running.handle.cancel(); + } + if !running.guarded_step(4096) { + break; + } + } + if let Ok(mut active) = shared.active.lock() { + *active = None; + } + } +} +#[cfg(test)] +mod retained_request_tests { + use super::*; + #[test] + fn retained_emitters_bill_vector_and_original_name_capacities_in_same_pool() { + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("fixture"); + let mut emissions = Vec::with_capacity(32); + emissions.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Front, + }); + let options = request.raytrace.as_mut().unwrap(); + options.emissions = Some(emissions); + let expected = 8 * std::mem::size_of::() as u64 + + 32 * std::mem::size_of::() as u64 + + 256; + assert_eq!(retained_request_bytes(&request).unwrap(), expected); + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: MEMORY_LIMIT }); + let lease = budget.reserve(expected).unwrap(); + assert_eq!(budget.used.load(Ordering::Acquire), expected); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected, expected).is_ok()); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected + 1, expected).is_err()); + drop(lease); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn emitter_request_lease_survives_real_completion_frame_eviction_and_last_handle() { + let mut host = CpuHost::for_platform().unwrap(); + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("emitter"); + let mut values = Vec::with_capacity(32); + values.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Both, + }); + request.raytrace.as_mut().unwrap().emissions = Some(values); + let expected = retained_request_bytes(&request).unwrap(); + let mesh = solidcraft_geom::Mesh { + positions: vec![solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, solidcraft_geom::Vec3::Y], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let job = host.submit(JobId { session: 1695, serial: 1, generation: 1 }, 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Completion publication precedes the worker's last temporary handle release. + // Join this test's worker before asserting exact lease ownership, as in the union test. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let held = job.clone(); + job.0.data.lock().unwrap().frame = None; + drop(job); + assert!(host.admitted_bytes() > expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + fn request() -> ImageRequest { + let mut lights = Vec::with_capacity(8); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(super::super::RaytraceOptions { lights: Some(lights), ..Default::default() }), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + } + } + #[test] + fn retained_lights_are_billed_by_original_capacity_and_sum_is_checked() { + let request = request(); + let bytes = retained_request_bytes(&request).unwrap(); + assert_eq!(bytes, 8 * std::mem::size_of::() as u64); + let cap = super::super::image::MAX_JOB_BYTES; + assert!(admit_request_sum(cap - bytes, bytes).is_ok()); + assert_eq!(admit_request_sum(cap - bytes + 1, bytes).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(admit_request_sum(u64::MAX, 1).unwrap_err().code, ErrorCode::LimitExceeded); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn retained_lights_keep_the_same_pool_lease_after_png_eviction() { + let host = CpuHost::for_platform().unwrap(); + let request = request(); + let expected = retained_request_bytes(&request).unwrap(); + let job = host + .submit( + JobId { session: 99, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + ) + .unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + let held_bytes = host.admitted_bytes(); + assert!(held_bytes > expected); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), held_bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod environment_metadata_lease_tests { + use super::*; + #[test] + fn captured_environment_metadata_survives_png_eviction_without_source_bytes() { + use crate::lighting::{ + HdrSource, + environment_input::{EnvironmentInfo, 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]); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap(); + let metadata = input.metadata(); + let expected = std::mem::size_of::() as u64; + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }; + let job = host + .submit_with_environment( + JobId { session: 1693, serial: 7, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + Some(input), + ) + .unwrap(); + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(matches!(status.environment, Some(JobEnvironmentInfo::Cpu(info)) if info.source_sha256 == metadata.source_sha256)); + host.join_worker_for_test().unwrap(); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(host); + drop(job); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod surface_request_metadata_tests { + use super::*; + use solidcraft_geom::{Aabb3, Mesh}; + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn surface_request_lease_survives_completion_frame_eviction_and_held_handles() { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use std::time::{Duration, Instant}; + fn settle(host: &CpuHost, expected: u64) { + let deadline = Instant::now() + Duration::from_secs(10); + while host.admitted_bytes() != expected && Instant::now() < deadline { + std::thread::yield_now(); + } + assert_eq!(host.admitted_bytes(), expected); + } + let mut host = CpuHost::for_platform().unwrap(); + let mut meshes = Vec::new(); + let mut effects = Vec::with_capacity(32); + for index in 0..32 { + let mut name = String::with_capacity(256); + name.push_str(&format!("{index:03}")); + name.push_str(&"x".repeat(253)); + assert_eq!(name.capacity(), 256); + meshes.push(ProductMesh { + transmission: None, + name: name.clone(), + mesh: Arc::new(Mesh::default()), + color: [100; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + effects.push(SurfaceEffect { + body: name, + frame: Default::default(), + repeat_mm: [20.0; 3], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }); + } + let scene = ProductScene { meshes, bounds: Aabb3 { min: solidcraft_geom::Vec3::ZERO, max: solidcraft_geom::Vec3::ZERO } }; + let mut request = request(); + request.integrator = Integrator::Raytrace; + request.raytrace = Some(super::super::RaytraceOptions { surface_effects: Some(effects), ..Default::default() }); + let metadata = retained_request_bytes(&request).unwrap(); + assert!(metadata >= 32 * 256); + let mut oversized = request.clone(); + let mut overallocated = Vec::with_capacity(64); + overallocated.extend(oversized.raytrace.as_mut().unwrap().surface_effects.take().unwrap()); + oversized.raytrace.as_mut().unwrap().surface_effects = Some(overallocated); + assert!(host.submit(id(40, 1), 1, scene.clone(), oversized).is_err()); + assert_eq!(host.admitted_bytes(), 0); + + let job = host.submit(id(40, 2), 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(Duration::from_secs(10)).unwrap().progress.phase, Phase::Completed); + // Wait for this host's last temporary worker handle before exact lease checks. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let png_bytes = frame._reservation.bytes; + settle(&host, metadata + png_bytes); + // Evict the record's frame under the same lock used by publication, while + // an external frame and a cloned job handle retain their independent leases. + job.0.data.lock().unwrap().frame = None; + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), metadata + png_bytes); + drop(frame); + settle(&host, metadata); + assert_eq!(held.status().unwrap().request.raytrace.unwrap().surface_effects.unwrap().len(), 32); + drop(held); + settle(&host, 0); + } + + fn request() -> ImageRequest { + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Default::default(), + raytrace: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } + } + + fn id(owner: u64, serial: u64) -> JobId { + JobId { session: owner, serial, generation: serial } + } +} + +/// Provisional source-film observation, separate from complete-pass previews. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PartialPreviewProjection { + TopLeftRepresentativeV1, +} +#[derive(Clone, Debug, Serialize)] +pub struct PartialPreviewInfo { + pub frame: FrameInfo, + pub sequence: u64, + pub source_width: u32, + pub source_height: u32, + pub completed_passes: u32, + pub updated_prefix: u64, + pub projection: PartialPreviewProjection, +} +/// Fields drop in declaration order: payload allocations die before credit return. +pub struct RenderPartialPreview { + pub info: PartialPreviewInfo, + png: Vec, + covered: Vec, + _lease: ReturnReservation, +} +const _: [(); 1] = [(); (std::mem::size_of::() + 2 * crate::MAX_RENDER_ID_BYTES + 256 <= 2048) as usize]; +impl RenderPartialPreview { + pub fn png(&self) -> &[u8] { + &self.png + } + pub fn covered(&self) -> &[u32] { + &self.covered + } +} +struct PartialCreditState { + report: Option, + free: Reservation, + in_flight: bool, + closed: bool, +} +struct PartialCredits { + protected: Option, + plan: super::PartialPreviewPlan, + state: Mutex, + requested: AtomicBool, + exhausted: AtomicBool, + _metadata: Reservation, +} +const _: [(); 1] = + [(); (std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::>() + 128 + <= 1024) as usize]; +impl PartialCredits { + fn new(plan: super::PartialPreviewPlan, reservation: &mut Reservation) -> Result> { + Self::new_with_protection(plan, None, reservation) + } + fn new_protected(plan: super::ProtectedPreviewPlan, reservation: &mut Reservation) -> Result> { + plan.validate()?; + Self::new_with_protection(plan.preview_plan(), Some(plan), reservation) + } + fn new_with_protection( + plan: super::PartialPreviewPlan, + protected: Option, + reservation: &mut Reservation, + ) -> Result> { + plan.validate()?; + let metadata = reservation.split(1024)?; + let bytes = plan.slot_bytes()?.checked_mul(2).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial credit overflow"))?; + let free = reservation.split(bytes)?; + Ok(Arc::new(Self { + plan, + protected, + state: Mutex::new(PartialCreditState { report: None, free, in_flight: false, closed: false }), + requested: AtomicBool::new(false), + exhausted: AtomicBool::new(false), + _metadata: metadata, + })) + } + fn request(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || self.exhausted.load(Ordering::Acquire) { + return Ok(false); + } + self.requested.store(true, Ordering::Release); + Ok(true) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + let bytes = self.plan.slot_bytes()?; + if state.closed + || state.in_flight + || self.exhausted.load(Ordering::Acquire) + || !self.requested.load(Ordering::Acquire) + || state.free.bytes < bytes + { + return Ok(None); + } + let reservation = state.free.split(bytes)?; + state.in_flight = true; + self.requested.store(false, Ordering::Release); + Ok(Some(ReturnReservation { reservation: Some(reservation), credits: self.clone(), in_flight: true })) + } + fn retained_slots_blocked(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial retention lock poisoned"))?; + Ok(!state.closed + && !state.in_flight + && !self.exhausted.load(Ordering::Acquire) + && self.requested.load(Ordering::Acquire) + && state.free.bytes < self.plan.slot_bytes()?) + } + fn exhaust(&self) { + self.exhausted.store(true, Ordering::Release); + self.requested.store(false, Ordering::Release); + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + state.in_flight = false; + self.requested.store(false, Ordering::Release); + // Atomic release only: no image destruction or user work under this lock. + let _ = state.free.shrink(0); + } +} +/// Unique lease; Arc payload clones never create another independent slot. +struct ReturnReservation { + reservation: Option, + credits: Arc, + in_flight: bool, +} +impl ReturnReservation { + fn published(&mut self) -> Result<()> { + let mut state = self.credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || !state.in_flight || !self.in_flight { + return Err(JobError::new(ErrorCode::Cancelled, "partial preview credit is no longer current")); + } + state.in_flight = false; + self.in_flight = false; + Ok(()) + } +} +impl Drop for ReturnReservation { + fn drop(&mut self) { + let Some(mut reservation) = self.reservation.take() else { return }; + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if self.in_flight { + state.in_flight = false; + } + if !state.closed { + let limit = self.credits.plan.slot_bytes().ok().and_then(|v| v.checked_mul(2)); + if state.free.bytes.checked_add(reservation.bytes).zip(limit).is_some_and(|(total, limit)| total <= limit) { + if state.free.merge_from(&mut reservation).is_err() { + state.closed = true; + let _ = state.free.shrink(0); + } + } else { + state.closed = true; + let _ = state.free.shrink(0); + } + } + drop(state); + // A closed sink releases this uniquely held reservation globally. + } +} +struct PartialPending { + covered: Vec, + completed_passes: u32, + updated_prefix: u64, +} +// Error paths preserve the same payload-before-lease destruction order. +struct PartialPublication { + png: Vec, + pending: PartialPending, + lease: ReturnReservation, +} +struct PartialRunning { + last_pass_attempt: u32, + pending: Option, + lease: Option, + credits: Arc, + next_sequence: u64, +} +impl PartialRunning { + fn new(credits: Arc) -> Self { + Self { pending: None, lease: None, credits, next_sequence: 1, last_pass_attempt: 0 } + } +} +impl JobHandle { + /// Real producer usage, unavailable until a protected task was actually constructed. + pub fn protected_preview_report(&self) -> Result> { + self.0.partial.as_ref().map_or(Ok(None), |credits| { + let state = credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + Ok(state.report) + }) + } + /// Request presentation only; this is not a visual-authority certificate. + pub fn request_partial_preview(&self) -> Result { + let terminal = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?.progress.phase.terminal(); + if terminal { + return Ok(false); + } + self.0.partial.as_ref().map_or(Ok(false), |credits| credits.request()) + } + pub fn partial_preview_exhausted(&self) -> Result { + Ok(self.0.partial.as_ref().is_some_and(|credits| credits.exhausted.load(Ordering::Acquire))) + } + pub fn partial_preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial preview lock poisoned"))?; + let preview = data.partial_preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "partial preview identity does not match its job")); + } + Ok(preview) + } +} +impl Running { + #[cfg(feature = "raytrace-cpu")] + fn capture_partial(&mut self, png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64) -> Result<()> { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without its policy"))?.get_mut()?; + let plan = partial.credits.plan; + let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height()); + let target = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without progressive intent"))? + .samples_per_pixel; + let covered_limit = plan.covered_bytes()?; + if partial.lease.is_none() + || partial.pending.is_some() + || completed_passes >= target + || updated_prefix >= source_pixels + || (completed_passes == 0 && updated_prefix == 0) + || covered.len() as u64 != plan.pixels() + || (covered.capacity() as u64).checked_mul(4).is_none_or(|v| v > covered_limit) + || png.capacity() as u64 > plan.encoded_limit()? + { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload exceeds its admitted frontier or capacities")); + } + // This sole sidecar verification scan was included in the producer's precharge. + for (index, count) in covered.iter().enumerate() { + self.handle.0.cancel.check()?; + let source = plan.source_index(index)? as u64; + let samples = completed_passes + .checked_add(u32::from(source < updated_prefix)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial sample count overflow"))?; + if *count > samples { + return Err(JobError::new(ErrorCode::Internal, "partial coverage exceeds committed source samples")); + } + } + partial.pending = Some(PartialPending { covered, completed_passes, updated_prefix }); + self.pending_png = Some(PendingPng::new(png)); + Ok(()) + } + fn publish_partial(&mut self, png: Vec, digest: sha2::digest::Output) -> Result { + 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"))?; + let lease = partial.lease.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication credit"))?; + let mut publication = PartialPublication { png, pending, lease }; + let sequence = partial.next_sequence; + let next = sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial preview sequence exhausted"))?; + let plan = partial.credits.plan; + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: plan.width(), + height: plan.height(), + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: publication.png.len() as u64, + png_sha256: format!("{:x}", digest), + }; + let metadata = std::mem::size_of::() + .checked_add(64 + 2 * crate::MAX_RENDER_ID_BYTES) + .and_then(|v| v.checked_add(info.png_sha256.capacity())); + if metadata.is_none_or(|v| v > 2048) { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload metadata exceeds its slot")); + } + // No Data lock while touching the credit coordinator. + publication.lease.published()?; + let PartialPublication { png, pending, lease } = publication; + let preview = Arc::new(RenderPartialPreview { + info: PartialPreviewInfo { + frame: info, + sequence, + source_width: plan.source_width(), + source_height: plan.source_height(), + completed_passes: pending.completed_passes, + updated_prefix: pending.updated_prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }, + png, + covered: pending.covered, + _lease: lease, + }); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial publication lock poisoned"))?; + if self.handle.0.cancel.is_cancelled() || data.progress.phase.terminal() { + drop(data); + drop(preview); + return Err(JobError::new(ErrorCode::Cancelled, "late partial preview refused")); + } + let released = data.partial_preview.replace(preview); + partial.next_sequence = next; + // A demand arriving during encoding remains pending; never clear it here. + drop(data); + drop(released); + self.handle.0.notify(); + Ok(true) + } +} + +impl PartialCredits { + fn policy(&self) -> CpuPreviewPolicy { + self.protected.map_or(CpuPreviewPolicy::Shared(self.plan), CpuPreviewPolicy::Protected) + } + fn store_report(&self, report: Option) -> Result<()> { + let (plan, report) = match (self.protected, report) { + (None, None) => return Ok(()), + (Some(plan), Some(report)) => (plan, report), + _ => return Err(JobError::new(ErrorCode::Internal, "producer work report differs from its admitted policy")), + }; + let presentation = plan.presentation_limit()?; + let aggregate = plan.aggregate_limit()?; + let expected_v = plan.snapshot_work()?.checked_mul(u64::from(report.accepted_snapshots)); + let used = report.ordinary_used.checked_add(report.presentation_used); + if report.policy_version != 1 + || report.ordinary_limit != plan.ordinary_limit() + || report.presentation_limit != presentation + || report.aggregate_limit != aggregate + || report.quota_limit != plan.quota_limit() + || report.ordinary_used > report.ordinary_limit + || report.presentation_used > presentation + || used.is_none_or(|v| v > aggregate) + || expected_v != Some(report.presentation_used) + || report.accepted_snapshots > report.next_milestone_index + || report.next_milestone_index > report.quota_limit + || report.quota_exhausted != (report.accepted_snapshots == report.quota_limit) + || report.milestones_complete != (report.next_milestone_index == report.quota_limit) + { + return Err(JobError::new(ErrorCode::Internal, "protected work report violates its actual admission")); + } + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + if state.report.is_some_and(|previous| { + previous.ordinary_used > report.ordinary_used + || previous.presentation_used > report.presentation_used + || previous.accepted_snapshots > report.accepted_snapshots + || previous.next_milestone_index > report.next_milestone_index + }) { + drop(state); + return Err(JobError::new(ErrorCode::Internal, "protected work report counters moved backwards")); + } + state.report = Some(report); + if report.quota_exhausted { + self.exhaust(); + } + Ok(()) + } +} + +impl WorkTask { + #[cfg(feature = "raytrace-cpu")] + fn raytrace_with_slot( + task: crate::raytrace::image::ImageTask, + report_sink: Option<&PartialCredits>, + make_slot: impl FnOnce(crate::raytrace::image::ImageTask) -> Result>, + ) -> Result { + // ImageTask is already real, even if its host wrapper cannot be allocated. + if let Some(credits) = report_sink { + credits.store_report(task.protected_preview_report())?; + } + make_slot(task).map(Self::Raytrace) + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host_regrade_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host_regrade_tests.rs new file mode 100644 index 000000000..8ec83b82f --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host_regrade_tests.rs @@ -0,0 +1,176 @@ +use super::super::{PngTask, linear_exr::ExrTask, presentation::Presentation}; +use super::*; +use std::sync::atomic::AtomicUsize; + +struct FixtureExecutor(Arc); +struct FixtureWork { + png: PngTask, + exr: Option>, +} +impl ImageWork for FixtureWork { + fn take_linear_exr(&mut self) -> Option> { + self.exr.take() + } + fn step(&mut self, units: usize) -> Result { + self.png.step(units) + } +} +impl ImageExecutor for FixtureExecutor { + fn supports_linear_exr(&self) -> bool { + true + } + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + let mut a = admit(scene, request)?; + a.estimated_total_bytes += 1_048_576; + Ok(a) + } + fn begin(&self, _: ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result> { + self.0.fetch_add(1, Ordering::Relaxed); + let pixels: Vec<_> = (0..request.width * request.height).map(|i| if i % 3 == 0 { [4.0, 0.5, 0.125, 0.5] } else { [0.0; 4] }).collect(); + let settings = Presentation { background: request.background, ..Default::default() }; + let mut rgba = vec![0; pixels.len() * 4]; + settings.display(request.width, request.height)?.encode(&pixels, &mut rgba, &cancel)?; + let exr = if options.linear_exr { + let mut task = ExrTask::new(request.width, request.height, pixels, cancel.clone())?; + while !task.step(4)? {} + Some(task.finish()?.0) + } else { + None + }; + Ok(Box::new(FixtureWork { png: PngTask::new(&request, rgba, cancel)?, exr })) + } +} +fn fixture(raw: bool) -> (ImageHost, JobHandle, Arc, Presentation) { + let begins = Arc::new(AtomicUsize::new(0)); + let host = ImageHost::cooperative_with(Arc::new(FixtureExecutor(begins.clone()))); + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + camera: Default::default(), + integrator: Default::default(), + raytrace: None, + textures: None, + environment: None, + }; + let settings = Presentation { background: request.background, ..Default::default() }; + let source = host + .submit_with_options( + identity(1), + 42, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + JobOptions { linear_exr: raw, ..Default::default() }, + ) + .unwrap(); + finish(&host, &source); + (host, source, begins, settings) +} +fn identity(serial: u64) -> JobId { + JobId { session: 1817, serial, generation: serial } +} +fn finish(host: &ImageHost, handle: &JobHandle) { + for _ in 0..4096 { + if !host.pump(4096).unwrap() { + break; + } + } + let status = handle.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); +} + +#[test] +fn an_empty_pixel_shows_the_background_code_unchanged() { + let display = Presentation { background: [40, 80, 120], ..Default::default() }.display(1, 1).unwrap(); + let mut rgba = [0; 4]; + display.encode(&[[0.0; 4]], &mut rgba, &CancelToken::default()).unwrap(); + assert_eq!(rgba, [40, 80, 120, 255]); +} + +#[test] +fn regrade_is_exact_nondestructive_geometry_free_and_flattens_repeated_master_ownership() { + let (host, source, begins, settings) = fixture(true); + let original = source.frame().unwrap().unwrap(); + let raw = original.linear_exr().unwrap().as_ptr(); + let identity = host.submit_regrade(identity(2), &source, settings).unwrap(); + finish(&host, &identity); + let neutral = identity.frame().unwrap().unwrap(); + assert_eq!(neutral.png(), original.png()); + assert_eq!(neutral.linear_exr().unwrap().as_ptr(), raw); + assert_eq!(neutral.info.scene_generation, 42); + assert_eq!(neutral.info.executor.as_str(), "linear-master"); + let origin = identity.status().unwrap().presentation.unwrap(); + assert_eq!(origin.source_job, source.id()); + assert_eq!(origin.master_job, source.id()); + assert_eq!(origin.master_sha256, original.linear_master_info().unwrap().sha256); + assert!(!origin.denoise_applied); + let changed = Presentation { + exposure_ev: -2.0, + finishing: super::super::finishing::Finishing { + saturation: 0.2, + bloom: Some(super::super::bloom::Bloom { strength: 0.4, radius: 2, threshold: 1.0 }), + ..Default::default() + }, + backdrop: Some(Default::default()), + ..settings + }; + let derivative = host.submit_regrade(super::regrade_tests::identity(3), &identity, changed).unwrap(); + finish(&host, &derivative); + let frame = derivative.frame().unwrap().unwrap(); + assert_ne!(frame.png(), original.png()); + assert_eq!(frame.linear_exr().unwrap().as_ptr(), raw); + assert!(Arc::ptr_eq(&frame.master_source().unwrap(), &original)); + assert_eq!(frame.presentation().unwrap().source_job, identity.id()); + assert_eq!(begins.load(Ordering::Relaxed), 1, "post-hoc presentation may never launch an executor"); + drop(source); + drop(identity); + drop(derivative); + drop(neutral); + drop(original); + assert!(host.admitted_bytes() > frame.png().len() as u64, "raw source and origin metadata leases remain live"); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn regrade_rejects_foreign_missing_or_invalid_masters_and_cancellation_never_publishes() { + let (host, no_raw, _, settings) = fixture(false); + let before = host.admitted_bytes(); + assert!(host.submit_regrade(identity(2), &no_raw, settings).is_err()); + assert_eq!(host.admitted_bytes(), before); + let (host, source, begins, settings) = fixture(true); + let before = host.admitted_bytes(); + assert!(host.submit_regrade(JobId { session: 7, ..identity(2) }, &source, settings).is_err()); + assert!(host.submit_regrade(source.id(), &source, settings).is_err()); + assert!(host.submit_regrade(identity(2), &source, Presentation { exposure_ev: f64::NAN, ..settings }).is_err()); + assert_eq!(host.admitted_bytes(), before); + for (serial, begin_work) in [(3, false), (4, true)] { + let job = host.submit_regrade(identity(serial), &source, settings).unwrap(); + if begin_work { + assert!(host.pump(1).unwrap()); + } + job.cancel().unwrap(); + for _ in 0..64 { + if !host.pump(1).unwrap() { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(job); + assert_eq!(host.admitted_bytes(), before); + } + assert_eq!(begins.load(Ordering::Relaxed), 1); + drop(source); + assert_eq!(host.admitted_bytes(), 0); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host_tests.rs new file mode 100644 index 000000000..0ac2d3b17 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/host_tests.rs @@ -0,0 +1,2622 @@ +use super::*; +use solidcraft_geom::{Aabb3, Mesh}; + +#[test] +fn raster_ev_status_and_task_capture_do_not_change_dynamic_fees_or_enter_registered_work() { + for rig in [None, Some(Vec::new())] { + let host = CpuHost::cooperative(); + let mut input = request(); + input.raster_lights = rig; + let zero = host.admit(&empty(), &input, JobOptions::default()).unwrap(); + input.raster_exposure_ev = 1.0; + assert_eq!(host.admit(&empty(), &input, JobOptions::default()).unwrap().estimated_total_bytes, zero.estimated_total_bytes); + let job = host.submit(id(840, 1), 1, empty(), input).unwrap(); + assert_eq!(job.status().unwrap().request.raster_exposure_ev, 1.0); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().request.raster_exposure_ev, 1.0); + } + let (host, _) = probe_host(1024); + let mut input = request(); + input.raster_exposure_ev = 1.0; + assert_eq!(host.admit(&empty(), &input, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(host.submit(id(841, 1), 1, empty(), input).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); +} + +#[test] +fn raster_rig_charges_original_and_task_capacity_then_retains_record_through_eviction() { + let host = CpuHost::cooperative(); + let legacy = host.admit(&empty(), &request(), JobOptions::default()).unwrap(); + let mut input = request(); + let mut lights = Vec::with_capacity(1); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }); + let capacity = lights.capacity(); + input.raster_lights = Some(lights); + let retained = (capacity * std::mem::size_of::()) as u64; + let task_fee = (8 * std::mem::size_of::()) as u64; + let admitted = host.admit(&empty(), &input, JobOptions::default()).unwrap(); + assert_eq!(admitted.estimated_total_bytes, legacy.estimated_total_bytes + task_fee); + let job = host.submit(id(830, 1), 1, empty(), input).unwrap(); + assert_eq!(host.admitted_bytes(), admitted.estimated_total_bytes + retained); + let status = job.status().unwrap(); + assert_eq!(status.request.raster_lights.as_ref().unwrap().len(), 1); + assert!(status.request.raster_lights.as_ref().unwrap().capacity() <= 8); + assert_eq!(job.0.request.raster_lights.as_ref().unwrap().capacity(), capacity); + // Caller-owned status metadata is outside the host lease lifetime. + drop(status); + drain(&host); + let held_frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert!(host.admitted_bytes() > retained); + drop(held_frame); + assert_eq!(host.admitted_bytes(), retained); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + // These counters test fees/lifetimes; declaration-order source review separately + // verifies request payload destruction precedes release of request credits. +} + +#[test] +fn raster_rig_cancel_retains_only_original_request_until_last_handle() { + let host = CpuHost::cooperative(); + let mut input = request(); + input.raster_lights = Some(vec![super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + let retained = input.raster_lights_retained_bytes().unwrap(); + let job = host.submit(id(831, 1), 1, empty(), input).unwrap(); + job.cancel().unwrap(); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(host.admitted_bytes(), retained); + drop(job); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn registered_and_interactive_routes_refuse_even_empty_raster_rigs_without_work() { + let (registered, _) = probe_host(1024); + let mut input = request(); + input.raster_lights = Some(Vec::new()); + assert_eq!(registered.admit(&empty(), &input, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.submit(id(832, 1), 1, empty(), input.clone()).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(registered.admitted_bytes(), 0); + assert!(!registered.pump(1).unwrap()); + assert!(super::super::interactive::cpu_request(&input).is_err()); + input.integrator = Integrator::Raytrace; + assert!(super::super::interactive::cpu_request(&input).is_err()); +} + +mod interactive { + use super::*; + use crate::job::{RaytraceOptions, interactive::*}; + use std::time::Duration; + + fn cpu() -> ImageRequest { + ImageRequest { integrator: Integrator::Raytrace, raytrace: Some(RaytraceOptions::default()), ..request() } + } + fn revision(visual_revision: u64) -> VisualRevision { + VisualRevision { scene_generation: 19, visual_revision } + } + fn ms(value: u64) -> Duration { + Duration::from_millis(value) + } + + #[test] + fn preview_fits_landscape_portrait_square_and_small_outputs_without_mutating_final_intent() { + for (width, height, expected) in + [(3840, 2160, (1024, 576)), (2160, 3840, (576, 1024)), (4096, 4096, (1024, 1024)), (81, 53, (81, 53)), (u32::MAX, 1, (1024, 1))] + { + let mut source = cpu(); + source.width = width; + source.height = height; + source.camera.roll = 0.37; + source.background = [19, 31, 97]; + source.studio_weights = Some([0.1, 0.2, 0.9]); + source.raytrace = Some(RaytraceOptions { primary_samples: 16, exposure_ev: -2.0, shadows: false, ..Default::default() }); + let before = serde_json::to_value(&source).unwrap(); + let preview = cpu_request(&source).unwrap(); + assert_eq!((preview.width, preview.height), expected); + assert_eq!(preview.camera, source.camera); + assert_eq!(preview.background, source.background); + assert_eq!(preview.studio_weights, source.studio_weights); + let options = preview.raytrace.unwrap(); + assert_eq!(options.progressive, Some(crate::job::CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.exposure_ev, -2.0); + assert!(!options.shadows); + assert_eq!(serde_json::to_value(source).unwrap(), before); + } + } + + #[test] + fn preview_refuses_incompatible_transport_and_invalid_input_without_erasing_it() { + let mut source = cpu(); + // A valid fixed thin sheet remains deliberately unsupported by progressive. + // Area/LED now has its positive preservation case below. + source.raytrace.as_mut().unwrap().dielectrics = vec![crate::job::DielectricOptions { + body_index: 0, + body_name: "Original sheet".into(), + boundary: crate::job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }]; + source.raytrace.as_ref().unwrap().validate().unwrap(); + let before = serde_json::to_value(&source).unwrap(); + assert!(cpu_request(&source).is_err()); + assert_eq!(serde_json::to_value(&source).unwrap(), before); + for source in [ + ImageRequest { transparent_background: true, ..cpu() }, + ImageRequest { width: 0, ..cpu() }, + request(), + ImageRequest { raytrace: Some(RaytraceOptions { primary_samples: 3, ..Default::default() }), ..cpu() }, + ] { + assert!(cpu_request(&source).is_err()); + } + } + + #[test] + fn preview_preserves_rectangle_and_led_sources_and_all_nonsampling_options() { + use crate::job::{ + CpuProgressiveOptions, DirectionalLightOptions, PunctualLightOptions, RaytraceEnvironmentOptions, RectangleLightOptions, ReflectionBody, + ReflectionMode, ReflectionOptions, led_strip::LedStripOptions, + }; + let rectangle = RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }; + let led = LedStripOptions { + center_mm: [5.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [0.25, 0.5, 1.0], + intensity: 3.0, + }; + for area_samples in [1, 4, 16, 64] { + let mut source = cpu(); + source.width = 3840; + source.height = 2160; + source.camera.roll = 0.37; + source.background = [19, 31, 97]; + let mut options = RaytraceOptions { + primary_samples: 16, + exposure_ev: 1.25, + shadows: false, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]), + punctual_lights: Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 20.0], + color: [1.0; 3], + intensity: 2.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.01, + cone: None, + }]), + area_lights: Some(vec![rectangle.clone()]), + area_samples: Some(area_samples), + seed: Some(73), + environment: Some(RaytraceEnvironmentOptions { color: [0.2, 0.3, 0.4], intensity: 2.0 }), + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: "Subject".into(), mode: ReflectionMode::RoughSpecular }], + samples: 16, + max_bounces: 3, + }), + ..Default::default() + }; + led.append_to(&mut options, area_samples).unwrap(); + options.validate().unwrap(); + source.raytrace = Some(options); + let before = serde_json::to_value(&source).unwrap(); + let mut expected = source.clone(); + expected.width = 1024; + expected.height = 576; + let expected_options = expected.raytrace.as_mut().unwrap(); + expected_options.primary_samples = 1; + expected_options.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }); + expected_options.reflections.as_mut().unwrap().samples = 1; + + let preview = cpu_request(&source).unwrap(); + assert_eq!( + serde_json::to_value(&preview).unwrap(), + serde_json::to_value(&expected).unwrap(), + "all request fields must survive except the explicitly chosen preview envelope" + ); + assert_eq!(preview.raytrace, expected.raytrace); + assert!(preview.environment.is_none() && preview.textures.is_none()); + let preview_options = preview.raytrace.as_ref().unwrap(); + assert_eq!(preview_options.area_lights.as_ref().unwrap().as_slice(), &[rectangle.clone(), led.rectangle().unwrap()]); + assert_eq!(preview_options.area_samples, Some(area_samples)); + assert_eq!(preview_options.seed, Some(73), "camera seed zero must not replace the area-pattern seed"); + assert_eq!(serde_json::to_value(&source).unwrap(), before, "the final request remains immutable"); + } + } + + #[test] + fn explicit_enable_settles_edits_and_keeps_only_one_capture_even_without_cad_revision_changes() { + let mut interactive = Interactive::new(9001); + interactive.edit(revision(1), ms(0)).unwrap(); + assert_eq!(interactive.state().unwrap(), State::Off); + assert!(interactive.capture(ms(1000)).unwrap().is_none()); + interactive.enable(revision(1), ms(1000)).unwrap(); + assert!(interactive.capture(ms(1199)).unwrap().is_none()); + interactive.edit(revision(2), ms(1199)).unwrap(); + assert!(interactive.capture(ms(1398)).unwrap().is_none()); + let b = interactive.capture(ms(1399)).unwrap().unwrap(); + assert_eq!(b.revision(), revision(2)); + assert!(interactive.accepts_capture(b)); + assert!(interactive.capture(ms(9999)).unwrap().is_none()); + interactive.edit(revision(3), ms(1400)).unwrap(); + assert!(!interactive.accepts_capture(b)); + // Delayed failure of B cannot poison C. + interactive.capture_failed(b, JobError::new(ErrorCode::InvalidScene, "old capture")); + assert_eq!(interactive.state().unwrap(), State::Updating); + let c = interactive.capture(ms(1600)).unwrap().unwrap(); + interactive.capture_failed(c, JobError::new(ErrorCode::InvalidScene, "current capture")); + assert!(!interactive.accepts_capture(c)); + assert_eq!(interactive.state().unwrap(), State::Error); + assert_eq!(interactive.error().unwrap().message, "current capture"); + assert!(interactive.capture(ms(9999)).unwrap().is_none(), "no automatic failure retry loop"); + interactive.resume(ms(2000)).unwrap(); + assert!(interactive.capture(ms(2200)).unwrap().is_some()); + } + + #[test] + fn pause_edits_final_priority_workspace_departure_and_clock_regression_do_not_start_jobs() { + let mut interactive = Interactive::new(9002); + interactive.enable(revision(1), ms(1000)).unwrap(); + assert!(interactive.capture(ms(999)).unwrap().is_none()); + interactive.pause().unwrap(); + interactive.edit(revision(2), ms(2000)).unwrap(); + assert_eq!(interactive.state().unwrap(), State::Paused); + assert!(interactive.capture(ms(3000)).unwrap().is_none()); + interactive.set_final_active(true, ms(3000)).unwrap(); + interactive.resume(ms(3000)).unwrap(); + assert!(interactive.capture(ms(4000)).unwrap().is_none()); + interactive.set_final_active(false, ms(4000)).unwrap(); + assert!(interactive.capture(ms(4199)).unwrap().is_none()); + assert_eq!(interactive.capture(ms(4200)).unwrap().unwrap().revision(), revision(2)); + interactive.disable().unwrap(); + assert_eq!(interactive.state().unwrap(), State::Off); + assert!(interactive.capture(ms(9999)).unwrap().is_none()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn host() -> CpuHost { + // Real native admission/worker steps, explicitly pumped like the existing + // checkpoint tests. No test clock sleeps, mock renderer or OS race. + ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn superseded_jobs_are_cancelled_and_foreign_jobs_remain_untouched() { + let host = host(); + let mut interactive = Interactive::new(9003); + interactive.enable(revision(1), ms(0)).unwrap(); + let a = interactive.capture(ms(200)).unwrap().unwrap(); + let first = host.submit(id(9003, 1), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(a, first.clone()).unwrap()); + interactive.edit(revision(2), ms(201)).unwrap(); + assert_eq!(first.status().unwrap().progress.phase, Phase::Cancelled); + assert!(interactive.current().is_none()); + let b = interactive.capture(ms(401)).unwrap().unwrap(); + // A delayed A admission must carry A's identity, not the pending B's. + let late = host.submit(a.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert_eq!(late.id(), a.job_id()); + assert_ne!(late.id(), b.job_id()); + assert!(!interactive.attach(a, late.clone()).unwrap()); + assert_eq!(late.status().unwrap().progress.phase, Phase::Cancelled); + // Drain cancelled queue entries before admitting another real job. + while let Some(work) = host.0.shared.queue.lock().unwrap().pop_front() { + drop(work); + } + let foreign = host.submit(id(9999, 1), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(b, foreign.clone()).unwrap()); + assert_eq!(foreign.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(interactive.state().unwrap(), State::Error); + interactive.disable().unwrap(); + drop(interactive); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(16).unwrap() { + break; + } + } + assert_eq!(foreign.status().unwrap().progress.phase, Phase::Completed, "the foreign job can still finish after our controller is closed"); + assert!(foreign.frame().unwrap().is_some()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn progressive_checkpoints_reach_target_and_final_suspension_releases_owned_work() { + let host = host(); + let mut interactive = Interactive::new(9004); + interactive.enable(revision(1), ms(0)).unwrap(); + let ticket = interactive.capture(ms(200)).unwrap().unwrap(); + let job = host.submit(id(9004, 1), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(ticket, job.clone()).unwrap()); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + let mut seen = Vec::new(); + for _ in 0..100_000 { + let more = running.advance(16).unwrap(); + if let Some(preview) = interactive.current().unwrap().preview().unwrap() { + let spp = preview.info.samples_per_pixel; + if seen.last() != Some(&spp) { + seen.push(spp); + } + } + if !more { + break; + } + } + assert_eq!(seen, [1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + assert!(job.frame().unwrap().is_some()); + assert!(!interactive.attach(ticket, job.clone()).unwrap(), "duplicate acknowledgement cannot restart or cancel the accepted job"); + interactive.set_final_active(true, ms(300)).unwrap(); + assert_eq!(interactive.state().unwrap(), State::Paused); + assert!(interactive.current().is_none()); + assert!(interactive.capture(ms(9999)).unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn same_scene_stale_serial_generation_and_delayed_success_after_failure_are_rejected() { + for mismatch in 0..3 { + let host = host(); + let mut interactive = Interactive::new(9005); + interactive.enable(revision(1), ms(0)).unwrap(); + let ticket = interactive.capture(ms(200)).unwrap().unwrap(); + let mut job_id = ticket.job_id(); + let mut scene_generation = ticket.revision().scene_generation; + match mismatch { + 0 => job_id.serial += 1, + 1 => job_id.generation += 1, + _ => scene_generation += 1, + } + let job = host.submit(job_id, scene_generation, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(ticket, job.clone()).unwrap()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(interactive.state().unwrap(), State::Error); + } + let host = host(); + let mut interactive = Interactive::new(9006); + interactive.enable(revision(1), ms(0)).unwrap(); + let ticket = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.capture_failed(ticket, JobError::new(ErrorCode::InvalidScene, "capture failed")); + let late = host.submit(ticket.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(ticket, late.clone()).unwrap()); + assert_eq!(late.status().unwrap().progress.phase, Phase::Cancelled); + assert!(interactive.current().is_none()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn delayed_ticket_cannot_cancel_the_current_handle_but_still_cancels_its_obsolete_job() { + let host = host(); + let mut interactive = Interactive::new(9007); + interactive.enable(revision(1), ms(0)).unwrap(); + let old = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.edit(revision(2), ms(201)).unwrap(); + let current = interactive.capture(ms(401)).unwrap().unwrap(); + let job = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(current, job.clone()).unwrap()); + assert!(!interactive.attach(old, job.clone()).unwrap()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + let obsolete = host.submit(old.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(!interactive.attach(old, obsolete.clone()).unwrap()); + assert_eq!(obsolete.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(interactive.current().unwrap().id(), current.job_id()); + drop(interactive); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn stale_ticket_cannot_cancel_current_job_before_acknowledgement() { + let host = host(); + let mut interactive = Interactive::new(9008); + interactive.enable(revision(1), ms(0)).unwrap(); + let old = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.edit(revision(2), ms(201)).unwrap(); + let current = interactive.capture(ms(401)).unwrap().unwrap(); + let job = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + // B is admitted but not yet acknowledged. A delayed A callback has no + // authority to cancel B, including before current() can return a handle. + assert!(interactive.current().is_none()); + assert!(interactive.accepts_capture(current)); + assert!(!interactive.accepts_capture(old)); + assert!(!interactive.attach(old, job.clone()).unwrap()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Queued); + assert!(interactive.current().is_none()); + assert_eq!(interactive.state().unwrap(), State::Updating); + assert!(interactive.attach(current, job.clone()).unwrap()); + assert!(!interactive.accepts_capture(current)); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(16).unwrap() { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert!(job.frame().unwrap().is_some()); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + drop(running); + drop(interactive); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn distinct_same_id_records_are_cancelled_but_current_handle_clones_finish() { + let host = host(); + let mut interactive = Interactive::new(9009); + interactive.enable(revision(1), ms(0)).unwrap(); + let old = interactive.capture(ms(200)).unwrap().unwrap(); + interactive.edit(revision(2), ms(201)).unwrap(); + let current = interactive.capture(ms(401)).unwrap().unwrap(); + let accepted = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert!(interactive.attach(current, accepted.clone()).unwrap()); + for callback in [old, current] { + // The host accepts an explicit JobId; submitting twice creates two + // records. Metadata equality is not actual admitted-work identity. + let duplicate = host.submit(current.job_id(), 19, empty(), cpu_request(&cpu()).unwrap()).unwrap(); + assert_eq!(accepted.id(), duplicate.id()); + assert!(!Arc::ptr_eq(&accepted.0, &duplicate.0)); + assert!(!interactive.attach(callback, duplicate.clone()).unwrap()); + assert_eq!(duplicate.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(accepted.status().unwrap().progress.phase, Phase::Queued); + assert!(Arc::ptr_eq(&interactive.current().unwrap().0, &accepted.0)); + // A second callback for the original Arc is harmless for both an + // obsolete ticket and the already acknowledged current ticket. + assert!(!interactive.attach(callback, accepted.clone()).unwrap()); + assert_eq!(accepted.status().unwrap().progress.phase, Phase::Queued); + } + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + for _ in 0..100_000 { + if !running.advance(16).unwrap() { + break; + } + } + assert_eq!(accepted.status().unwrap().progress.phase, Phase::Completed); + assert!(accepted.frame().unwrap().is_some()); + assert_eq!(interactive.state().unwrap(), State::TargetReached); + while let Some(work) = host.0.shared.queue.lock().unwrap().pop_front() { + assert_eq!(work.handle.status().unwrap().progress.phase, Phase::Cancelled); + drop(work); + } + drop(running); + drop(interactive); + drop(accepted); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod progressive_checkpoints { + use super::*; + use crate::job::{CpuProgressiveOptions, RaytraceOptions}; + + // The production native admission/Running path, manually advanced so tests + // can stop exactly between hashing and the cancellation/publication lock. + fn fixture(samples: u32) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 4, + height: 4, + ..request() + }; + let expected = admit(&empty(), &request).unwrap().estimated_total_bytes; + let job = host.submit(id(7300, 1), 19, empty(), request).unwrap(); + assert_eq!(host.admitted_bytes(), expected); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + + fn fixture_with_cadence(samples: u32, every_pass: bool) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + cpu_progressive_every_pass: every_pass, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 4, + height: 4, + ..request() + }; + let expected = admit(&empty(), &request).unwrap().estimated_total_bytes; + let job = host.submit(id(7300, 1), 19, empty(), request).unwrap(); + assert_eq!(host.admitted_bytes(), expected); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + + #[test] + fn captured_legacy_cadence_reaches_real_worker_checkpoints_and_keeps_final_bytes_identical() { + for (target, sparse) in [(3, vec![1, 2]), (5, vec![1, 2, 4]), (9, vec![1, 2, 4, 8])] { + let mut baseline: Option> = None; + for every_pass in [true, false] { + let (host, job, mut running) = fixture_with_cadence(target, every_pass); + let mut samples = Vec::new(); + let mut last_sequence = 0; + let mut complete = false; + for _ in 0..100_000 { + let more = running.advance(1).unwrap(); + if let Some(preview) = job.preview().unwrap() + && preview.info.frame_sequence != last_sequence + { + last_sequence = preview.info.frame_sequence; + samples.push(preview.info.samples_per_pixel); + } + assert_eq!(job.status().unwrap().request.cpu_progressive_every_pass, every_pass); + if !more { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(samples, if every_pass { (1..target).collect::>() } else { sparse.clone() }); + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 0); + let frame = job.frame().unwrap().unwrap(); + if let Some(expected) = &baseline { + assert_eq!(frame.png(), expected.as_slice()); + } else { + baseline = Some(frame.png().to_vec()); + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + drop(frame); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + } + } + + #[test] + fn legacy_cadence_cancellation_during_hashing_cannot_publish_or_release_a_live_payload_early() { + let (host, job, mut running) = fixture_with_cadence(9, false); + before_preview(&mut running); + assert!(running.pending_png.is_some()); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + fn before_preview(running: &mut Running) { + for _ in 0..100_000 { + if running.pending_png.as_ref().is_some_and(|p| p.preview_samples.is_some()) { + return; + } + assert!(running.advance(1).unwrap()); + } + panic!("small CPU job did not reach its checkpoint"); + } + + #[test] + fn checkpoints_transfer_png_allocations_and_keep_every_external_lease() { + let (host, job, mut running) = fixture(3); + let initial = host.admitted_bytes(); + let mut held = Vec::new(); + for (sequence, samples) in [(1, 1), (2, 2)] { + before_preview(&mut running); + let pointer = running.pending_png.as_ref().unwrap().png.as_ptr(); + assert!(running.task.is_some(), "a preview must retain film, BVH and task state"); + assert!(running.advance(1).unwrap()); + let preview = job.preview().unwrap().unwrap(); + assert_eq!(preview.png().as_ptr(), pointer, "PNG ownership moves without cloning its allocation"); + assert_eq!(preview.info.frame_sequence, sequence); + assert_eq!(preview.info.samples_per_pixel, samples); + assert_eq!(preview.info.frame.job, job.id()); + assert_eq!(preview.info.frame.scene_generation, 19); + assert_eq!(preview.info.frame.png_sha256, format!("{:x}", Sha256::digest(preview.png()))); + assert!(job.frame().unwrap().is_none()); + assert!(job.status().unwrap().frame.is_none()); + assert_eq!(host.admitted_bytes(), initial, "splitting a prepaid lease does not change pool usage"); + held.push(preview); + } + let mut complete = false; + for _ in 0..100_000 { + if !running.advance(1).unwrap() { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert!(job.preview().unwrap().is_none()); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, job.id()); + let retained: u64 = held.iter().map(|p| p._reservation.bytes).sum(); + assert_eq!(host.admitted_bytes(), retained + frame._reservation.bytes); + drop(running); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), retained); + while let Some(preview) = held.pop() { + let before = host.admitted_bytes(); + let bytes = preview._reservation.bytes; + drop(preview); + assert_eq!(host.admitted_bytes(), before - bytes); + } + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn cancellation_before_or_after_digest_cannot_publish_a_late_preview() { + for finish_digest in [false, true] { + let (host, job, mut running) = fixture(3); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let held = job.preview().unwrap().unwrap(); + before_preview(&mut running); + if finish_digest { + let pending = running.pending_png.as_mut().unwrap(); + while !pending.step(1, &job.0.cancel).unwrap() {} + assert_eq!(pending.hashed, pending.png.len()); + } + job.cancel().unwrap(); + assert!(job.preview().unwrap().is_none(), "cancel removes the provisional slot immediately"); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), held._reservation.bytes); + assert_eq!(held.info.samples_per_pixel, 1); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + + #[test] + fn an_invalid_checkpoint_sequence_fails_without_replacing_the_old_snapshot() { + let (host, job, mut running) = fixture(4); + before_preview(&mut running); + assert!(running.advance(1).unwrap()); + let held = job.preview().unwrap().unwrap(); + before_preview(&mut running); + running.pending_png.as_mut().unwrap().preview_samples = Some(3); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(held.info.samples_per_pixel, 1); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), held._reservation.bytes); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } +} + +fn request() -> ImageRequest { + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Default::default(), + raytrace: None, + textures: None, + environment: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } +} + +#[test] +fn legacy_image_requests_default_to_raster_and_reject_unknown_integrators() { + let mut value = serde_json::to_value(request()).unwrap(); + value.as_object_mut().unwrap().remove("integrator"); + let decoded: ImageRequest = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(decoded.integrator, Integrator::Raster); + value["integrator"] = serde_json::json!("gpu_pathtrace"); + assert!(serde_json::from_value::(value).is_err()); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn cooperative_raytrace_descriptor_matches_native_only_validation() { + let host = CpuHost::cooperative(); + assert!(host.validate_integrator(Integrator::Raytrace).is_err()); + assert!(matches!(host.descriptor_for(Integrator::Raytrace).unwrap().availability, Availability::Unavailable { .. })); + assert!(host.validate_integrator(Integrator::Raster).is_ok()); + assert!(!host.descriptor_for(Integrator::Raytrace).unwrap().profiles.iter().any(|p| p.features.contains(&crate::RenderFeature::Refraction))); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn native_raytrace_refraction_capability_resolves_only_preview_images() { + let host = CpuHost::for_platform().unwrap(); + let descriptor = host.descriptor_for(Integrator::Raytrace).unwrap(); + assert_eq!(descriptor.availability, Availability::Available); + assert!(descriptor.profiles.iter().any(|profile| profile.features.contains(&crate::RenderFeature::Refraction))); + let mut backend = crate::builtin_backend(); + backend.executors = vec![descriptor]; + let mut request = crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: 1, + height: 1, + format: Some(RenderFormat::Png), + features: vec![crate::RenderFeature::Refraction], + policy: Default::default(), + }; + let resolved = crate::resolve_request(std::slice::from_ref(&backend), &request).unwrap(); + assert_eq!(resolved.executor.as_str(), "cpu-raytrace"); + request.mode = RenderMode::Final; + assert!(crate::resolve_request(std::slice::from_ref(&backend), &request).is_err()); + request.mode = RenderMode::Preview; + backend.executors = vec![host.descriptor_for(Integrator::Raster).unwrap()]; + assert!(crate::resolve_request(&[backend], &request).is_err(), "CPU raster must not advertise physical refraction"); + assert_eq!(host.admitted_bytes(), 0, "capability discovery never starts a render"); +} + +#[cfg(not(feature = "raytrace-cpu"))] +#[test] +fn compiled_out_raytracing_never_enters_the_host_queue() { + let host = CpuHost::cooperative(); + let mut request = request(); + request.integrator = Integrator::Raytrace; + assert!(host.validate_integrator(Integrator::Raytrace).unwrap_err().message.contains("not compiled in")); + assert!(host.descriptor_for(Integrator::Raytrace).is_err()); + let error = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 0, empty(), request).err().unwrap(); + assert_eq!(error.code, ErrorCode::HostUnavailable); + assert_eq!(host.admitted_bytes(), 0); + assert!(!host.pump(1).unwrap()); +} +fn empty() -> ProductScene { + ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY } +} +fn id(owner: u64, serial: u64) -> JobId { + JobId { session: owner, serial, generation: serial } +} +fn drain(host: &CpuHost) { + for _ in 0..10_000 { + if !host.pump(4096).unwrap() { + return; + } + } + panic!("small cooperative jobs did not drain"); +} + +#[test] +fn queue_is_bounded_and_cancelled_entries_release_their_reservations() { + let host = CpuHost::cooperative(); + let a = host.submit(id(10, 1), 100, empty(), request()).unwrap(); + let b = host.submit(id(20, 1), 200, empty(), request()).unwrap(); + let before = host.admitted_bytes(); + assert_eq!(host.submit(id(30, 1), 300, empty(), request()).err().unwrap().code, ErrorCode::QueueFull); + assert_eq!(host.admitted_bytes(), before); + assert_eq!(a.cancel().unwrap().progress.phase, Phase::Cancelled); + let c = host.submit(id(30, 1), 300, empty(), request()).unwrap(); + drain(&host); + assert_eq!(a.status().unwrap().progress.phase, Phase::Cancelled); + for (handle, owner, generation) in [(&b, 20, 200), (&c, 30, 300)] { + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.job, id(owner, 1)); + assert_eq!(frame.info.scene_generation, generation); + assert_eq!(frame.info.executor.as_str(), "cpu-product"); + assert_eq!(image::load_from_memory(frame.png()).unwrap().width(), 16); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(handle.status().unwrap().frame.unwrap().png_sha256, frame.info.png_sha256); + } + assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < before); + let frame = b.frame().unwrap().unwrap(); + drop(b); + drop(c); + assert!(host.admitted_bytes() > 0, "an externally retained frame retains its lease"); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cancellation_while_encoding_cannot_publish_a_late_frame() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 8, empty(), request()).unwrap(); + for _ in 0..10_000 { + host.pump(64).unwrap(); + let status = job.status().unwrap(); + if status.progress.phase == Phase::Encoding && status.progress.done > 0 { + break; + } + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Encoding); + assert_eq!(job.cancel().unwrap().progress.phase, Phase::Cancelling); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn malformed_preparation_fails_the_job_without_stopping_the_host() { + let host = CpuHost::cooperative(); + let scene = ProductScene { + bounds: Aabb3::EMPTY, + meshes: vec![crate::ProductMesh { + name: "Broken".into(), + mesh: Arc::new(Mesh { triangles: vec![[99, 99, 99]], ..Default::default() }), + color: [0; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + }; + let broken = host.submit(id(1, 1), 1, scene, request()).unwrap(); + drain(&host); + let status = broken.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Failed); + assert_eq!(status.error.unwrap().code, ErrorCode::InvalidScene); + assert!(status.frame.is_none(), "a failed preparation path has no cached PNG identity"); + assert!(broken.frame().unwrap().is_none()); + assert!(host.is_available()); + let healthy = host.submit(id(1, 2), 1, empty(), request()).unwrap(); + drain(&host); + assert_eq!(healthy.status().unwrap().progress.phase, Phase::Completed); +} + +#[test] +fn closing_the_host_cancels_active_and_queued_work() { + let host = CpuHost::cooperative(); + let budget = host.0.shared.budget.clone(); + let active = host.submit(id(1, 1), 1, empty(), request()).unwrap(); + let queued = host.submit(id(2, 1), 1, empty(), request()).unwrap(); + host.pump(1).unwrap(); + drop(host); + assert_eq!(active.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(queued.status().unwrap().progress.phase, Phase::Cancelled); + assert_eq!(budget.used.load(Ordering::Acquire), 0); +} + +#[test] +fn a_foreign_frame_is_rejected_even_if_a_broken_host_puts_it_in_the_result_slot() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 1, empty(), request()).unwrap(); + drain(&host); + { + let mut data = job.0.data.lock().unwrap(); + let frame = Arc::get_mut(data.frame.as_mut().unwrap()).unwrap(); + frame.info.job.session = 2; + } + assert_eq!(job.frame().err().unwrap().code, ErrorCode::WrongOwner); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_job_finishes_without_any_poll_or_ui_pump() { + let host = CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), HostKind::NativeWorker); + let job = host.submit(id(1, 1), 12, empty(), request()).unwrap(); + // A generous deadlock watchdog, not a performance assertion. + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(job.frame().unwrap().unwrap().info.scene_generation, 12); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); +} + +/// Isolate the existing integrator-to-host completion boundary with a real PNG +/// from the production encoder. This does not pretend to render the noisy pixels. +fn pending_digest_fixture() -> (CpuHost, JobHandle, Running, usize) { + let host = CpuHost::cooperative(); + let mut request = request(); + request.width = 256; + request.height = 128; + let mut rgba = vec![255; request.width as usize * request.height as usize * 4]; + let mut seed = 0x6a09_e667u32; + for pixel in rgba.as_chunks_mut::<4>().0 { + for channel in pixel.iter_mut().take(3) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + *channel = seed as u8; + } + } + let mut encoder = super::super::encoding::PngEncoding::new( + request.width, + request.height, + u64::from(request.width) * u64::from(request.height) * 8 + 65_536, + CancelToken::default(), + ) + .unwrap(); + let png = loop { + if let Some(png) = encoder.step(&rgba).unwrap() { + break png; + } + }; + assert!(png.len() > PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE); + let length = png.len(); + let job = host.submit(id(61, 1), 99, empty(), request).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + // Exactly the same state transition used when WorkTask returns Complete. + running.task = None; + running.pending_png = Some(PendingPng::new(png)); + (host, job, running, length) +} + +#[test] +fn png_digest_is_incremental_and_keeps_the_original_allocation_and_lease_until_completion() { + let (host, job, mut running, length) = pending_digest_fixture(); + let before = host.admitted_bytes(); + let pointer = running.pending_png.as_ref().unwrap().png.as_ptr(); + assert!(running.advance(0).unwrap()); + assert_eq!(running.pending_png.as_ref().unwrap().hashed, 0, "zero units cannot hash a chunk"); + assert_eq!(host.admitted_bytes(), before); + assert!(job.frame().unwrap().is_none()); + assert!(running.advance(usize::MAX).unwrap()); + assert_eq!(running.pending_png.as_ref().unwrap().hashed, PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE); + assert_eq!(host.admitted_bytes(), before, "hashing must retain the full original work lease"); + assert!(job.frame().unwrap().is_none()); + let mut previous = job.status().unwrap().progress.done; + while running.advance(1).unwrap() { + let progress = job.status().unwrap().progress; + assert_eq!(progress.phase, Phase::Encoding); + assert_eq!(progress.total, length as u64); + assert_eq!(progress.done - previous, PNG_HASH_CHUNK_BYTES as u64); + assert_eq!(host.admitted_bytes(), before); + assert!(job.frame().unwrap().is_none()); + previous = progress.done; + } + assert!(running.task.is_none() && running.pending_png.is_none() && running.reservation.is_none()); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.png().as_ptr(), pointer, "the original Vec moves into the retained frame without cloning"); + assert_eq!(frame.info.png_bytes, length as u64); + assert_eq!(frame.info.png_sha256.len(), 64); + assert!(frame.info.png_sha256.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))); + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); + let decoded = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (256, 128)); + assert!(decoded.pixels().all(|p| p.0[3] == 255)); + assert!(decoded.pixels().any(|p| p.0[..3] != decoded.get_pixel(0, 0).0[..3])); + let actual_metadata = + std::mem::size_of::() + std::mem::size_of::() + frame.info.png_sha256.capacity() + 2 * crate::MAX_RENDER_ID_BYTES + 32; + assert!(actual_metadata <= FRAME_METADATA_BYTES as usize, "digest Vec/offset/state and actual hex allocation must be admitted"); + assert_eq!(host.admitted_bytes(), frame.png.capacity() as u64 + FRAME_METADATA_BYTES); + for _ in 0..3 { + let current = job.status().unwrap(); + assert_eq!(current.frame.unwrap().png_sha256, frame.info.png_sha256); + assert_eq!(frame.png().as_ptr(), pointer); + } + drop(running); + drop(job); + assert!(host.admitted_bytes() > 0); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cancellation_during_png_hashing_and_host_disposal_cannot_publish_a_frame() { + for close_host in [false, true] { + let (host, job, running, _) = pending_digest_fixture(); + let budget = host.0.shared.budget.clone(); + *host.0.running.lock().unwrap() = Some(running); + assert!(host.pump(1).unwrap()); + assert!(host.0.running.lock().unwrap().as_ref().unwrap().pending_png.as_ref().unwrap().hashed > 0); + assert_eq!(job.status().unwrap().progress.phase, Phase::Encoding); + assert!(job.frame().unwrap().is_none()); + if close_host { + drop(host); + } else { + assert_eq!(job.cancel().unwrap().progress.phase, Phase::Cancelling); + assert!(!host.pump(1).unwrap()); + drop(host); + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} + +#[test] +fn a_cancel_after_the_last_digest_chunk_still_wins_the_publication_lock() { + let (host, job, mut running, _) = pending_digest_fixture(); + let pending = running.pending_png.as_mut().unwrap(); + while !pending.step(1, &job.0.cancel).unwrap() {} + assert_eq!(pending.hashed, pending.png.len()); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(running); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn png_digest_metadata_fits_the_existing_allowance_without_changing_admission() { + // Fixed digest/offset state and the completed frame (including its bounded + // hex string and backend/executor IDs) fit the existing 1024-byte allowance. + assert!(std::mem::size_of::() <= 512); + assert!( + std::mem::size_of::() + std::mem::size_of::() + 64 + 2 * crate::MAX_RENDER_ID_BYTES + 32 + <= FRAME_METADATA_BYTES as usize + ); + let host = CpuHost::cooperative(); + let expected = admit(&empty(), &request()).unwrap().estimated_total_bytes; + let job = host.submit(id(70, 1), 1, empty(), request()).unwrap(); + assert_eq!(host.admitted_bytes(), expected); + assert!(job.status().unwrap().frame.is_none()); + job.cancel().unwrap(); + drain(&host); + assert_eq!(host.admitted_bytes(), 0); +} + +/// An executor whose task reports, as it is dropped, how much of the pool is admitted, and +/// completes after `steps` steps (or never, cancelled on its last one with `cancel_last`). +struct DropProbe { + admitted_at_drop: Arc, + budget: Arc>>, + estimated: u64, +} +struct ProbeTask { + admitted_at_drop: Arc, + budget: Arc>>, + steps: u32, +} +impl Drop for ProbeTask { + fn drop(&mut self) { + let used = self.budget.get().map_or(u64::MAX, |b| b.used.load(Ordering::Acquire)); + self.admitted_at_drop.store(used, Ordering::Release); + } +} +impl ImageWork for ProbeTask { + fn step(&mut self, _units: usize) -> Result { + self.steps += 1; + if self.steps < 3 { + return Ok(TaskPoll::Pending(Progress { phase: Phase::Running, done: u64::from(self.steps), total: 3 })); + } + Ok(TaskPoll::Complete(vec![0u8; 100])) + } +} +impl ImageExecutor for DropProbe { + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, _: &ProductScene, _: &ImageRequest, _: JobOptions) -> Result { + Ok(Admission { + triangles: 0, + face_appearances: 0, + geometry_bytes: 0, + pixel_scratch_bytes: self.estimated, + preparation_bytes: 0, + estimated_total_bytes: self.estimated, + encoded_limit: 4096, + }) + } + fn begin(&self, _: ProductScene, _: ImageRequest, _: JobOptions, _: CancelToken) -> Result> { + Ok(Box::new(ProbeTask { admitted_at_drop: self.admitted_at_drop.clone(), budget: self.budget.clone(), steps: 0 })) + } +} + +fn probe_host(estimated: u64) -> (CpuHost, Arc) { + let admitted_at_drop = Arc::new(AtomicU64::new(0)); + let budget = Arc::new(std::sync::OnceLock::new()); + let host = CpuHost::cooperative_with(Arc::new(DropProbe { admitted_at_drop: admitted_at_drop.clone(), budget: budget.clone(), estimated })); + let _ = budget.set(host.0.shared.budget.clone()); + (host, admitted_at_drop) +} + +#[test] +fn a_completed_task_is_dropped_while_its_full_reservation_still_pays_for_it() { + let estimated = 1 << 20; + let (host, admitted_at_drop) = probe_host(estimated); + let job = host.submit(id(1, 1), 1, empty(), request()).unwrap(); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + // While the task (and its scratch) was being dropped, its whole charge was still held. + assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated); + // Afterwards only the PNG's lease remains, and the frame keeps it. + let frame = job.frame().unwrap().unwrap(); + assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < estimated, "{}", host.admitted_bytes()); + drop(job); + drop(frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn a_cancel_on_the_final_step_publishes_no_frame_and_drops_the_task() { + let estimated = 1 << 20; + let (host, admitted_at_drop) = probe_host(estimated); + let job = host.submit(id(1, 1), 1, empty(), request()).unwrap(); + // Two pending steps, then cancel before the step that would complete. + host.pump(1).unwrap(); + host.pump(1).unwrap(); + job.cancel().unwrap(); + drain(&host); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + assert_eq!(admitted_at_drop.load(Ordering::Acquire), estimated, "the task went before its charge"); + assert_eq!(host.admitted_bytes(), 0); +} + +#[test] +fn cpu_and_registered_hosts_keep_separate_job_limits() { + let cpu = CpuHost::cooperative(); + let (registered, _) = probe_host(400 * 1024 * 1024); + assert_eq!(cpu.job_limit_bytes(), 384 * 1024 * 1024); + assert_eq!(registered.job_limit_bytes(), 512 * 1024 * 1024); + assert_eq!(cpu.pool_limit_bytes(), registered.pool_limit_bytes()); + assert_eq!(registered.pool_limit_bytes(), 512 * 1024 * 1024); + assert_eq!(registered.admit(&empty(), &request(), JobOptions::default()).unwrap().estimated_total_bytes, 400 * 1024 * 1024); + assert_eq!(admit_request_sum(400 * 1024 * 1024, 0).unwrap_err().code, ErrorCode::LimitExceeded); + let (over_budget, _) = probe_host(512 * 1024 * 1024 + 1); + assert_eq!(over_budget.admit(&empty(), &request(), JobOptions::default()).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(registered.admitted_bytes(), 0); +} + +#[test] +fn registered_hosts_refuse_cpu_integrators_and_options_before_reservation() { + let (registered, _) = probe_host(1024 * 1024); + let mut raytrace = request(); + raytrace.integrator = Integrator::Raytrace; + assert_eq!(registered.validate_integrator(Integrator::Raytrace).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.descriptor_for(Integrator::Raytrace).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.admit(&empty(), &raytrace, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.submit(id(250, 1), 1, empty(), raytrace).err().unwrap().code, ErrorCode::InvalidRequest); + let mut options = request(); + options.raytrace = Some(super::super::RaytraceOptions::default()); + assert_eq!(registered.admit(&empty(), &options, JobOptions::default()).unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(registered.admitted_bytes(), 0); + assert!(!registered.pump(1).unwrap()); +} + +#[test] +fn environment_payload_is_owned_by_admitted_work_not_retained_status() { + struct ResourceExecutor; + impl ImageExecutor for ResourceExecutor { + fn descriptor(&self) -> Result { + let mut descriptor = CpuExecutor.descriptor()?; + descriptor.profiles[0].features.push(crate::RenderFeature::Hdri); + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + let mut admission = admit(scene, &ImageRequest { environment: None, textures: None, ..request.clone() })?; + admission.estimated_total_bytes += request.environment.as_ref().map_or(0, |source| source.admitted_bytes()); + Ok(admission) + } + fn begin(&self, scene: ProductScene, mut request: ImageRequest, _: JobOptions, cancel: CancelToken) -> Result> { + request.environment = None; + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } + } + for cancelled in [false, true] { + let host = ImageHost(Arc::new(Owner { + executor: Some(Arc::new(ResourceExecutor)), + shared: ImageHost::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })); + let source = Arc::new(crate::lighting::environment::EnvironmentSource::sky(Default::default(), 0.0, 1.0).unwrap()); + let weak = Arc::downgrade(&source); + let mut input = request(); + input.environment = Some(source); + let job = host.submit(id(1, 1), 1, empty(), input).unwrap(); + let status = job.status().unwrap(); + assert!(status.request.environment.is_none()); + assert!(matches!(status.environment.as_ref(), Some(JobEnvironmentInfo::Gpu(info)) if info.kind == "original_gradient_sky")); + assert!(weak.upgrade().is_some(), "queuedwork owns source"); + if cancelled { + job.cancel().unwrap(); + } + drain(&host); + assert!(weak.upgrade().is_none(), "completed/cancelled work releases captured source despite retained status/job"); + assert_eq!(job.status().unwrap().progress.phase, if cancelled { Phase::Cancelled } else { Phase::Completed }); + } +} + +#[test] +fn texture_payload_is_owned_by_admitted_work_not_retained_status() { + struct ResourceExecutor; + impl ImageExecutor for ResourceExecutor { + fn descriptor(&self) -> Result { + let mut descriptor = CpuExecutor.descriptor()?; + descriptor.profiles[0].features.push(crate::RenderFeature::Hdri); + Ok(descriptor) + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, _: JobOptions) -> Result { + let mut admission = admit(scene, &ImageRequest { environment: None, textures: None, ..request.clone() })?; + admission.estimated_total_bytes += request.textures.as_ref().map_or(0, |source| source.working_bytes()); + Ok(admission) + } + fn begin(&self, scene: ProductScene, mut request: ImageRequest, _: JobOptions, cancel: CancelToken) -> Result> { + request.textures = None; + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } + } + for cancelled in [false, true] { + let host = ImageHost(Arc::new(Owner { + executor: Some(Arc::new(ResourceExecutor)), + shared: ImageHost::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })); + use crate::job::textures::{PlanarFrame, RuntimeTextures, TextureBinding, TextureMap}; + use image::ImageEncoder; + let mut bytes = Vec::new(); + image::codecs::png::PngEncoder::new(&mut bytes).write_image(&[128, 128, 255, 255], 1, 1, image::ExtendedColorType::Rgba8).unwrap(); + let source = Arc::new( + RuntimeTextures::new(vec![TextureBinding { + body_index: 0, + body_name: "unused test resource".into(), + frame: PlanarFrame { origin: [0.; 3], u: [1., 0., 0.], v: [0., 1., 0.] }, + normal_strength: 1., + base_color: Some(TextureMap::new(bytes, crate::texture_input::MapRole::BaseColor).unwrap()), + normal: None, + roughness: None, + metallic: None, + base_color_mode: Default::default(), + flip_v: false, + }]) + .unwrap(), + ); + let weak = Arc::downgrade(&source); + let mut input = request(); + input.textures = Some(source); + let job = host.submit(id(1, 1), 1, empty(), input).unwrap(); + let status = job.status().unwrap(); + assert!(status.request.textures.is_none()); + assert_eq!(status.textures.as_ref().unwrap().bodies, 1); + assert!(weak.upgrade().is_some(), "queuedwork owns source"); + if cancelled { + job.cancel().unwrap(); + } + drain(&host); + assert!(weak.upgrade().is_none(), "completed/cancelled work releases captured source despite retained status/job"); + assert_eq!(job.status().unwrap().progress.phase, if cancelled { Phase::Cancelled } else { Phase::Completed }); + } +} + +#[test] +fn cpu_film_snapshots_refuse_registered_executors_without_acquiring_a_lease() { + let (host, _) = probe_host(1 << 20); + let failure = host.reserve_film_snapshot(1024).err().unwrap(); + assert_eq!(failure.code, ErrorCode::InvalidRequest); + assert!(failure.message.contains("builtin CPU host")); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn native_cpu_envelopes_do_not_expand_registered_or_cooperative_pools() { + use super::super::{CpuBudget, NATIVE_CPU_POOL_BYTES, RaytraceOptions}; + let cpu = CpuHost::for_platform().unwrap(); + let cooperative = CpuHost::cooperative(); + let (registered, _) = probe_host(1024); + assert_eq!(cpu.pool_limit_bytes(), NATIVE_CPU_POOL_BYTES); + assert_eq!(cooperative.pool_limit_bytes(), 512 * 1024 * 1024); + assert_eq!(registered.pool_limit_bytes(), 512 * 1024 * 1024); + assert!(cpu.check_request_sum(400 * 1024 * 1024, 0, CpuBudget::Compact).is_err()); + assert!(cpu.check_request_sum(400 * 1024 * 1024, 0, CpuBudget::Studio).is_ok()); + assert!(cpu.check_request_sum(u64::MAX, 1, CpuBudget::Workstation).is_err()); + let mut r = request(); + r.integrator = Integrator::Raytrace; + r.width = 3840; + r.height = 2160; + r.raytrace = Some(RaytraceOptions { budget: CpuBudget::Studio, ..Default::default() }); + assert_eq!(cpu.descriptor_for_request(&r).unwrap().limits, CpuBudget::Studio.image_limits(false)); + r.raytrace.as_mut().unwrap().budget = CpuBudget::Compact; + assert!(cpu.descriptor_for_request(&r).is_err()); + assert_eq!(cpu.admitted_bytes(), 0); +} + +#[cfg(all(not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn registered_large_pool_is_explicit_finite_and_accounted() { + struct Envelope(u64); + impl ImageExecutor for Envelope { + fn memory_limit_bytes(&self) -> u64 { + self.0 + } + fn descriptor(&self) -> Result { + CpuExecutor.descriptor() + } + fn admit(&self, _: &ProductScene, _: &ImageRequest, _: JobOptions) -> Result { + Ok(Admission { + triangles: 0, + face_appearances: 0, + geometry_bytes: 0, + pixel_scratch_bytes: 0, + preparation_bytes: 0, + estimated_total_bytes: 600 * 1024 * 1024, + encoded_limit: 4096, + }) + } + fn begin(&self, _: ProductScene, _: ImageRequest, _: JobOptions, _: CancelToken) -> Result> { + Err(JobError::new(ErrorCode::InvalidRequest, "admission-only fixture")) + } + } + for limit in [0, super::super::NATIVE_CPU_POOL_BYTES + 1] { + assert!(ImageHost::with_executor(Arc::new(Envelope(limit))).is_err()); + } + let host = ImageHost::with_executor(Arc::new(Envelope(1024 * 1024 * 1024))).unwrap(); + assert_eq!(host.pool_limit_bytes(), 1024 * 1024 * 1024); + assert!(host.admit(&empty(), &request(), JobOptions::default()).is_ok()); + assert_eq!(host.admitted_bytes(), 0, "preflight does not allocate or reserve"); + let lease = host.0.shared.budget.reserve(600 * 1024 * 1024).unwrap(); + assert!(host.0.shared.budget.reserve(600 * 1024 * 1024).is_err()); + drop(lease); + assert_eq!(host.admitted_bytes(), 0); +} + +mod partial_preview_contract { + use super::*; + use crate::job::PartialPreviewPlan; + + fn credits() -> (Arc, Reservation, Arc) { + let plan = PartialPreviewPlan::new(4, 1).unwrap(); + let total = 2 * plan.slot_bytes().unwrap() + 1024 + 17; + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: total }); + let mut work = budget.reserve(total).unwrap(); + let credits = PartialCredits::new(plan, &mut work).unwrap(); + assert_eq!(work.bytes, 17); + (budget, work, credits) + } + fn take(credits: &Arc) -> ReturnReservation { + assert!(credits.request().unwrap()); + credits.acquire().unwrap().unwrap() + } + fn payload(mut lease: ReturnReservation, sequence: u64) -> Arc { + lease.published().unwrap(); + Arc::new(RenderPartialPreview { + info: PartialPreviewInfo { + frame: FrameInfo { + job: id(7724, 1), + scene_generation: 19, + backend: crate::builtin_backend().id, + executor: ExecutorId::new("cpu-raytrace").unwrap(), + width: 4, + height: 1, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: 4, + png_sha256: "unit-lease-fixture".into(), + }, + sequence, + source_width: 4, + source_height: 1, + completed_passes: 0, + updated_prefix: 1, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }, + png: vec![1, 2, 3, 4], + covered: vec![1, 0, 0, 0], + _lease: lease, + }) + } + #[test] + fn plan_is_canonical_no_upscale_and_maps_top_left_without_source_scan() { + for (w, h, expected) in [(16384, 4096, (1024, 256)), (2160, 3840, (576, 1024)), (4, 1, (4, 1)), (u32::MAX, 1, (1024, 1))] { + let plan = PartialPreviewPlan::new(w, h).unwrap(); + assert_eq!((plan.width(), plan.height()), expected); + assert_eq!((plan.source_width(), plan.source_height()), (w, h)); + assert_eq!(plan.source_index(0).unwrap(), 0); + assert!(plan.source_index(plan.pixels() as usize).is_err()); + assert!(plan.pixels() <= 1024 * 1024); + } + let plan = PartialPreviewPlan::new(16384, 4096).unwrap(); + assert_eq!(plan.source_index(1025).unwrap(), 16 * 16384 + 16); + assert_eq!(plan.snapshot_work().unwrap(), 14 * 1024 * 256 + 65538); + assert!(PartialPreviewPlan::new(0, 1).is_err()); + assert!(PartialPreviewPlan::new(1, 0).is_err()); + } + #[test] + fn same_budget_merge_moves_ownership_once_and_wrong_pool_preserves_both() { + let a = Arc::new(Budget { used: AtomicU64::new(0), limit: 100 }); + let b = Arc::new(Budget { used: AtomicU64::new(0), limit: 100 }); + let mut retained = a.reserve(80).unwrap(); + let mut donor = retained.split(30).unwrap(); + let mut foreign = b.reserve(9).unwrap(); + assert_eq!(retained.merge_from(&mut foreign).unwrap_err().code, ErrorCode::WrongOwner); + assert_eq!((retained.bytes, foreign.bytes), (50, 9)); + retained.merge_from(&mut donor).unwrap(); + assert_eq!((retained.bytes, donor.bytes, a.used.load(Ordering::Acquire)), (80, 0, 80)); + assert!(retained.split(81).is_err()); + assert_eq!(retained.bytes, 80); + drop(donor); + assert_eq!(a.used.load(Ordering::Acquire), 80); + drop(retained); + drop(foreign); + assert_eq!((a.used.load(Ordering::Acquire), b.used.load(Ordering::Acquire)), (0, 0)); + } + #[test] + fn two_total_slots_include_inflight_and_clones_do_not_mint_capacity() { + let (budget, work, credits) = credits(); + let total = budget.used.load(Ordering::Acquire); + let first = take(&credits); + assert!(credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none(), "one encoder even with another free slot"); + let first = payload(first, 1); + let held = first.clone(); + let second = payload(take(&credits), 2); + assert!(credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none()); + assert!(credits.requested.load(Ordering::Acquire), "full credit preserves coalesced demand"); + drop(first); + assert!(credits.acquire().unwrap().is_none(), "a clone retains the same first slot"); + assert_eq!(budget.used.load(Ordering::Acquire), total); + drop(held); + let third = credits.acquire().unwrap().unwrap(); + assert_eq!(budget.used.load(Ordering::Acquire), total, "return/transfer does not reserve globally again"); + assert_eq!(second.png(), &[1, 2, 3, 4]); + drop(third); + drop(second); + credits.close(); + assert_eq!(budget.used.load(Ordering::Acquire), 17 + 1024); + drop(credits); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn demand_during_inflight_survives_publication_and_terminal_held_frames_stay_billed() { + let (budget, work, credits) = credits(); + let first = take(&credits); + assert!(!credits.requested.load(Ordering::Acquire)); + assert!(credits.request().unwrap()); + let first = payload(first, 1); + assert!(credits.requested.load(Ordering::Acquire)); + let second = payload(credits.acquire().unwrap().unwrap(), 2); + let per_slot = credits.plan.slot_bytes().unwrap(); + credits.close(); + assert!(!credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none()); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 2 * per_slot + 1024); + drop(credits); + assert_eq!(first.covered(), &[1, 0, 0, 0]); + drop(first); + assert_eq!(budget.used.load(Ordering::Acquire), per_slot + 1024); + drop(second); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn optional_exhaustion_is_real_and_legacy_request_remains_noop() { + let (_, work, credits) = credits(); + assert!(credits.request().unwrap()); + credits.exhaust(); + assert!(credits.exhausted.load(Ordering::Acquire)); + assert!(!credits.request().unwrap()); + assert!(credits.acquire().unwrap().is_none()); + credits.close(); + drop(work); + let host = CpuHost::cooperative(); + let job = host.submit(id(7724, 2), 19, empty(), request()).unwrap(); + let before = serde_json::to_value(job.status().unwrap()).unwrap(); + assert!(!job.request_partial_preview().unwrap()); + assert!(!job.partial_preview_exhausted().unwrap()); + assert!(job.partial_preview().unwrap().is_none()); + assert_eq!(serde_json::to_value(job.status().unwrap()).unwrap(), before); + job.cancel().unwrap(); + assert!(!job.request_partial_preview().unwrap()); + } + + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + fn real_fixture() -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(crate::job::RaytraceOptions { + progressive: Some(crate::job::CpuProgressiveOptions { samples_per_pixel: 5, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 16, + height: 16, + ..request() + }; + let job = host.submit_cpu_partial_with_environment_and_options(id(7724, 3), 19, empty(), request, JobOptions::default(), None).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn real_partial_png_carries_unknown_and_two_held_payloads_do_not_block_final() { + let (host, job, mut running) = real_fixture(); + assert!(job.request_partial_preview().unwrap()); + let mut during = false; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if !during && running.partial.as_ref().unwrap().0[0].lease.is_some() { + assert!(job.request_partial_preview().unwrap()); + during = true; + } + if job.partial_preview().unwrap().is_some() { + break; + } + } + let first = job.partial_preview().unwrap().unwrap(); + assert!(during); + assert_eq!(first.info.sequence, 1); + assert_eq!(first.info.completed_passes, 0); + assert!(first.info.updated_prefix > 0 && first.info.updated_prefix < 256); + assert!(job.preview().unwrap().is_none(), "partial mode never publishes uncredited legacy snapshots"); + let decoded = image::load_from_memory(first.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (16, 16)); + for (i, rgba) in decoded.pixels().enumerate() { + assert_eq!(rgba.0[3], if (i as u64) < first.info.updated_prefix { 255 } else { 0 }); + assert_eq!(first.covered()[i], 0, "empty scene means a real miss, never a fabricated hit"); + } + let first_hash = Sha256::digest(first.png()); + for _ in 0..100_000 { + if job.partial_preview().unwrap().is_some_and(|p| p.info.sequence == 2) { + break; + } + assert!(running.advance(1).unwrap()); + } + let second = job.partial_preview().unwrap().unwrap(); + assert_eq!(second.info.sequence, 2, "request issued during encoding must survive first publication"); + assert!(job.request_partial_preview().unwrap()); + assert_eq!(job.0.partial.as_ref().unwrap().state.lock().unwrap().free.bytes, 0); + for _ in 0..100_000 { + if !running.advance(1).unwrap() { + break; + } + assert!(job.partial_preview().unwrap().is_some_and(|p| p.info.sequence == 2)); + assert!(running.partial.as_ref().unwrap().0[0].lease.is_none()); + assert!(running.partial.as_ref().unwrap().0[0].pending.is_none()); + } + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let final_frame = job.frame().unwrap().unwrap(); + assert_eq!((final_frame.info.width, final_frame.info.height), (16, 16)); + assert!(job.partial_preview().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + assert_eq!(Sha256::digest(first.png()), first_hash); + let per_slot = job.0.partial.as_ref().unwrap().plan.slot_bytes().unwrap(); + drop(running); + let before = host.admitted_bytes(); + drop(first); + assert_eq!(host.admitted_bytes(), before - per_slot); + drop(second); + assert_eq!(host.admitted_bytes(), before - 2 * per_slot); + drop(final_frame); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod partial_preview_terminal_errors { + use super::*; + use crate::job::{CpuProgressiveOptions, RaytraceOptions}; + + #[test] + fn cancellation_during_real_partial_hash_closes_slots_and_publishes_nothing() { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 7 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 8, + height: 8, + ..request() + }; + let job = host.submit_cpu_partial_with_environment_and_options(id(7725, 1), 19, empty(), request, JobOptions::default(), None).unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let mut running = Running::begin(work).unwrap(); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if running.pending_png.is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + assert!(running.pending_png.is_some()); + assert!(job.partial_preview().unwrap().is_none()); + assert!(running.partial.as_ref().unwrap().0[0].pending.is_some()); + job.cancel().unwrap(); + assert!(!job.request_partial_preview().unwrap()); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.partial_preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[test] +fn partial_credit_last_drop_fails_closed_after_poison_without_losing_leases() { + let plan = crate::job::PartialPreviewPlan::new(1, 1).unwrap(); + let bytes = 2 * plan.slot_bytes().unwrap() + 1024; + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: bytes }); + let mut work = budget.reserve(bytes).unwrap(); + let credits = PartialCredits::new(plan, &mut work).unwrap(); + credits.request().unwrap(); + let held = credits.acquire().unwrap().unwrap(); + let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _state = credits.state.lock().unwrap(); + panic!("deliberate test-only credit lock poison"); + })); + assert!(poisoned.is_err()); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 1024); + credits.close(); + drop(credits); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 0); +} + +mod protected_feedback_contract { + use super::*; + use crate::job::{CpuBudget, MAX_CPU_WORK, MAX_PROTECTED_CPU_WORK, ProtectedPreviewPlan, ProtectedPreviewReport}; + + #[test] + fn profile_ordinary_caps_are_unchanged_and_protected_aggregate_is_explicit() { + assert_eq!(MAX_CPU_WORK, 16_000_000_000_000); + assert_eq!(MAX_PROTECTED_CPU_WORK, 31_462_813_335_678); + for (profile, ordinary) in + [(CpuBudget::Compact, 1_000_000_000), (CpuBudget::Studio, 1_000_000_000_000), (CpuBudget::Workstation, MAX_CPU_WORK)] + { + let plan = ProtectedPreviewPlan::new(1024, 1024, 16, profile).unwrap(); + plan.validate().unwrap(); + assert_eq!(plan.ordinary_limit(), ordinary); + assert_eq!(plan.quota_limit(), 79); + assert_eq!(plan.snapshot_work().unwrap(), 14_745_602); + assert_eq!(plan.presentation_limit().unwrap(), 1_164_902_558); + assert_eq!(plan.aggregate_limit().unwrap(), ordinary + 1_164_902_558); + assert_eq!(plan.preview_plan(), crate::job::PartialPreviewPlan::new(1024, 1024).unwrap()); + } + let largest = ProtectedPreviewPlan::new(1024, 1024, 16, CpuBudget::Workstation).unwrap(); + assert!( + largest.aggregate_limit().unwrap() < MAX_PROTECTED_CPU_WORK, + "the independent Cartesian ceiling need not be attained by this request" + ); + } + #[test] + fn zero_single_and_spread_milestones_are_checked_below_final_target() { + let zero = ProtectedPreviewPlan::new(1, 1, 1, CpuBudget::Compact).unwrap(); + assert_eq!((zero.total_commits(), zero.quota_limit(), zero.presentation_limit().unwrap()), (1, 0, 0)); + assert_eq!(zero.aggregate_limit().unwrap(), zero.ordinary_limit()); + assert!(zero.milestone(0).is_err()); + let single = ProtectedPreviewPlan::new(2, 1, 1, CpuBudget::Compact).unwrap(); + assert_eq!(single.quota_limit(), 1); + assert_eq!(single.milestone(0).unwrap(), 1); + assert!(single.milestone(1).is_err()); + for (w, h, spp, quota, last) in [(3, 1, 1, 2, 2), (66, 1, 1, 64, 65), (32, 32, 64, 127, 64_512)] { + let plan = ProtectedPreviewPlan::new(w, h, spp, CpuBudget::Compact).unwrap(); + assert_eq!(plan.quota_limit(), quota); + let milestones: Vec<_> = (0..quota).map(|j| plan.milestone(j).unwrap()).collect(); + assert_eq!(milestones.first(), Some(&1)); + assert_eq!(milestones.last(), Some(&last)); + assert!(milestones.windows(2).all(|pair| pair[0] < pair[1])); + assert!(plan.milestone(quota).is_err()); + assert!(plan.milestone(u32::MAX).is_err()); + } + } + #[test] + fn protected_plan_preserves_explicit_large_profiles_and_rejects_invalid_inputs() { + let large = ProtectedPreviewPlan::new(4096, 4096, 4096, CpuBudget::Workstation).unwrap(); + assert_eq!(large.samples_per_pixel(), 4096); + assert_eq!(large.budget(), CpuBudget::Workstation); + assert_eq!(large.total_commits(), 68_719_476_736); + assert_eq!((large.preview_plan().width(), large.preview_plan().height()), (1024, 1024)); + assert!(large.aggregate_limit().unwrap() <= MAX_PROTECTED_CPU_WORK); + for (w, h, spp, budget) in [ + (0, 1, 1, CpuBudget::Compact), + (1, 0, 1, CpuBudget::Compact), + (1, 1, 0, CpuBudget::Compact), + (1, 1, 65, CpuBudget::Compact), + (u32::MAX, u32::MAX, u32::MAX, CpuBudget::Workstation), + (4096, 4096, 4096, CpuBudget::Compact), + ] { + assert!(ProtectedPreviewPlan::new(w, h, spp, budget).is_err()); + } + } + + // Synthetic REPORT-validation fixtures only; real producer usage is tested below. + fn report(plan: ProtectedPreviewPlan, ordinary_used: u64, accepted: u32, next: u32) -> ProtectedPreviewReport { + ProtectedPreviewReport { + policy_version: 1, + ordinary_limit: plan.ordinary_limit(), + presentation_limit: plan.presentation_limit().unwrap(), + aggregate_limit: plan.aggregate_limit().unwrap(), + ordinary_used, + presentation_used: u64::from(accepted) * plan.snapshot_work().unwrap(), + accepted_snapshots: accepted, + quota_limit: plan.quota_limit(), + next_milestone_index: next, + quota_exhausted: accepted == plan.quota_limit(), + milestones_complete: next == plan.quota_limit(), + } + } + fn credits(plan: ProtectedPreviewPlan) -> (Arc, Reservation, Arc) { + let total = 2 * plan.preview_plan().slot_bytes().unwrap() + 1024; + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: total }); + let mut work = budget.reserve(total).unwrap(); + let credits = PartialCredits::new_protected(plan, &mut work).unwrap(); + assert_eq!(work.bytes, 0); + (budget, work, credits) + } + #[test] + fn coalesced_milestones_do_not_fabricate_spent_quota_or_permanent_exhaustion() { + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let (budget, work, credits) = credits(plan); + assert!(credits.state.lock().unwrap().report.is_none()); + let value = report(plan, 31, 1, 127); + credits.store_report(Some(value)).unwrap(); + assert_eq!(credits.state.lock().unwrap().report, Some(value)); + assert!(value.milestones_complete && !value.quota_exhausted); + assert_eq!(value.presentation_used, 79_874); + assert!(value.presentation_used < value.presentation_limit); + assert!(!credits.exhausted.load(Ordering::Acquire)); + assert!(credits.request().unwrap()); + assert!(credits.state.lock().unwrap().report == Some(value)); + credits.close(); + drop(credits); + drop(work); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn actual_report_invariants_and_monotonic_refusals_preserve_the_prior_observation() { + let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap(); + let (_, work, credits) = credits(plan); + let good = report(plan, 31, 1, 2); + credits.store_report(Some(good)).unwrap(); + let bad = [ + report(plan, 30, 1, 2), + report(plan, 31, 0, 2), + report(plan, 31, 1, 1), + ProtectedPreviewReport { ordinary_used: plan.ordinary_limit() + 1, ..good }, + ProtectedPreviewReport { presentation_used: plan.presentation_limit().unwrap() + 1, ..good }, + ProtectedPreviewReport { aggregate_limit: MAX_PROTECTED_CPU_WORK + 1, ..good }, + ProtectedPreviewReport { quota_exhausted: true, ..good }, + ProtectedPreviewReport { milestones_complete: true, ..good }, + ProtectedPreviewReport { policy_version: 2, ..good }, + ]; + for value in bad { + assert!(credits.store_report(Some(value)).is_err()); + assert_eq!(credits.state.lock().unwrap().report, Some(good)); + } + assert!(credits.store_report(None).is_err()); + assert_eq!(credits.state.lock().unwrap().report, Some(good)); + let at_limits = report(plan, plan.ordinary_limit(), plan.quota_limit(), plan.quota_limit()); + credits.store_report(Some(at_limits)).unwrap(); + assert_eq!(at_limits.ordinary_used + at_limits.presentation_used, at_limits.aggregate_limit); + assert!(credits.exhausted.load(Ordering::Acquire)); + assert!(!credits.request().unwrap()); + credits.close(); + drop(credits); + drop(work); + } + #[test] + fn legacy_report_is_absent_and_rejected_protected_admission_does_not_reserve() { + let host = CpuHost::cooperative(); + let job = host.submit(id(7730, 1), 19, empty(), request()).unwrap(); + let before = serde_json::to_value(job.status().unwrap()).unwrap(); + assert!(job.protected_preview_report().unwrap().is_none()); + assert_eq!(serde_json::to_value(job.status().unwrap()).unwrap(), before); + let admitted = host.admitted_bytes(); + assert!( + host.submit_cpu_protected_partial_with_environment_and_options(id(7730, 2), 19, empty(), request(), JobOptions::default(), None).is_err() + ); + assert_eq!(host.admitted_bytes(), admitted); + assert!(job.protected_preview_report().unwrap().is_none()); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod protected_feedback_real_host { + use super::*; + use crate::job::{CpuProgressiveOptions, RaytraceOptions}; + + fn fixture(serial: u64, width: u32, height: u32, samples: u32) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width, + height, + background: [10, 20, 30], + ..request() + }; + let job = host + .submit_cpu_protected_partial_with_environment_and_options(id(7731, serial), 19, empty(), request, JobOptions::default(), None) + .unwrap(); + assert!(job.protected_preview_report().unwrap().is_none(), "no future ledger is invented while queued"); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + assert!(job.protected_preview_report().unwrap().is_some(), "report is read from the real constructed task"); + (host, job, running) + } + fn finish(running: &mut Running) { + for _ in 0..1_000_000 { + if !running.advance(1).unwrap() { + return; + } + } + panic!("small protected CPU fixture did not finish"); + } + #[test] + fn actual_32_by_32_control_and_feedback_keep_ordinary_work_and_final_png_identical() { + let (control_host, control, mut control_run) = fixture(1, 32, 32, 64); + finish(&mut control_run); + let control_report = control.protected_preview_report().unwrap().unwrap(); + let control_frame = control.frame().unwrap().unwrap(); + assert_eq!(control_report.presentation_used, 5_032_062); + assert_eq!(control_report.accepted_snapshots, 63); + assert!(control_report.ordinary_used > 0); + let (host, job, mut running) = fixture(2, 32, 32, 64); + assert!(job.request_partial_preview().unwrap()); + finish(&mut running); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(report.ordinary_used, control_report.ordinary_used); + assert_eq!(report.ordinary_limit, 1_000_000_000); + assert_eq!(report.accepted_snapshots, 64); + assert_eq!(report.presentation_used, 5_111_936); + assert_eq!(report.ordinary_used + report.presentation_used, control_report.ordinary_used + 5_111_936); + assert_eq!(report.presentation_used - control_report.presentation_used, 79_874); + assert_eq!(report.aggregate_limit, report.ordinary_limit + report.presentation_limit); + assert!(!report.quota_exhausted); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.png(), control_frame.png()); + let decoded = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (32, 32)); + assert!(decoded.pixels().all(|p| p.0 == [10, 20, 30, 255]), "analytic all-miss final pixels"); + let terminal = job.protected_preview_report().unwrap(); + assert!(!job.request_partial_preview().unwrap()); + assert_eq!(job.protected_preview_report().unwrap(), terminal); + drop(frame); + drop(job); + drop(running); + drop(control_frame); + drop(control); + drop(control_run); + assert_eq!((host.admitted_bytes(), control_host.admitted_bytes()), (0, 0)); + } + #[test] + fn real_quota_exhaustion_does_not_remove_normal_full_pass_or_final_work() { + let (control_host, control, mut control_run) = fixture(3, 2, 1, 2); + finish(&mut control_run); + let expected = control.protected_preview_report().unwrap().unwrap(); + let control_frame = control.frame().unwrap().unwrap(); + let (host, job, mut running) = fixture(4, 2, 1, 2); + let mut exhausted_seen = false; + for _ in 0..100_000 { + job.request_partial_preview().unwrap(); + let more = running.advance(1).unwrap(); + let report = job.protected_preview_report().unwrap().unwrap(); + if report.quota_exhausted { + exhausted_seen = true; + assert!(job.partial_preview_exhausted().unwrap()); + assert!(!job.request_partial_preview().unwrap()); + } + if !more { + break; + } + } + assert!(exhausted_seen); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!((report.accepted_snapshots, report.quota_limit, report.next_milestone_index), (2, 2, 2)); + assert!(report.quota_exhausted && report.milestones_complete); + assert_eq!(report.presentation_used, report.presentation_limit); + assert_eq!(report.ordinary_used, expected.ordinary_used, "full-pass tick and final remain ordinary"); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.png(), control_frame.png()); + drop(frame); + drop(job); + drop(running); + drop(control_frame); + drop(control); + drop(control_run); + assert_eq!((host.admitted_bytes(), control_host.admitted_bytes()), (0, 0)); + } + #[test] + fn two_retained_protected_payloads_keep_their_leases_without_blocking_final() { + let (host, job, mut running) = fixture(5, 2, 1, 2); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if job.partial_preview().unwrap().is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + let first = job.partial_preview().unwrap().unwrap(); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if job.partial_preview().unwrap().is_some_and(|p| p.info.sequence == 2) { + break; + } + assert!(running.advance(1).unwrap()); + } + let second = job.partial_preview().unwrap().unwrap(); + assert_eq!(second.info.sequence, 2); + let old_hash = Sha256::digest(first.png()); + assert!(job.request_partial_preview().unwrap()); + assert_eq!(job.0.partial.as_ref().unwrap().state.lock().unwrap().free.bytes, 0); + finish(&mut running); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!((report.accepted_snapshots, report.quota_limit), (2, 2)); + assert!(report.quota_exhausted); + assert_eq!(Sha256::digest(first.png()), old_hash); + drop(running); + let slot = job.0.partial.as_ref().unwrap().plan.slot_bytes().unwrap(); + let retained = host.admitted_bytes(); + drop(first); + assert_eq!(host.admitted_bytes(), retained - slot); + drop(second); + assert_eq!(host.admitted_bytes(), retained - 2 * slot); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn charged_begin_followed_by_poll_error_retains_actual_report_without_refund() { + let (host, job, mut running) = fixture(6, 32, 32, 64); + let plan = job.0.partial.as_ref().unwrap().plan; + for _ in 0..100_000 { + if running.task.as_mut().unwrap().partial_ready(plan).unwrap() { + break; + } + assert!(running.advance(1).unwrap()); + } + assert!(running.task.as_mut().unwrap().partial_ready(plan).unwrap()); + assert!(job.request_partial_preview().unwrap()); + // Invalid zero quantum fails AFTER the host's accepted safe BEGIN/precharge. + assert!(!running.guarded_step(0)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(report.accepted_snapshots, 1); + assert_eq!(report.presentation_used, 79_874); + assert!(job.frame().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn cancellation_while_host_hashes_does_not_charge_twice_or_refund_feedback() { + let (host, job, mut running) = fixture(7, 32, 32, 64); + assert!(job.request_partial_preview().unwrap()); + for _ in 0..100_000 { + if running.pending_png.is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + assert!(running.pending_png.is_some()); + let before = job.protected_preview_report().unwrap().unwrap(); + assert_eq!((before.accepted_snapshots, before.presentation_used), (1, 79_874)); + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.protected_preview_report().unwrap(), Some(before)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.frame().unwrap().is_none()); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod protected_begin_setup_errors { + use super::*; + use crate::job::{CpuProgressiveOptions, EmissionSides, RaytraceOptions, SurfaceEmission}; + use solidcraft_geom::Vec3; + + fn fixture(serial: u64) -> (CpuHost, JobHandle, Work) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let mesh = Arc::new(Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![crate::ProductMesh { + name: "Setup witness".into(), + mesh, + color: [0; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + }; + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 2, seed: 123 }), + lights: Some(Vec::new()), + emissions: Some(vec![SurfaceEmission { + body_index: 0, + body: "Setup witness".into(), + color: [1.0, 0.0, 0.0], + strength: 2.0, + sides: EmissionSides::Both, + }]), + ..Default::default() + }), + width: 2, + height: 1, + ..request() + }; + assert_eq!(request.raytrace.as_ref().unwrap().emissions.as_ref().unwrap().len(), 1); + let job = host + .submit_cpu_protected_partial_with_environment_and_options(id(7732, serial), 19, scene, request, JobOptions::default(), None) + .unwrap(); + assert!(job.protected_preview_report().unwrap().is_none()); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + (host, job, work) + } + fn observed_report(credits: &PartialCredits) -> crate::job::ProtectedPreviewReport { + let Ok(state) = credits.state.try_lock() else { panic!("wrapping factory must run outside the report/credit lock") }; + let actual = state.report.expect("real task report must be captured BEFORE fallible wrapping"); + assert_eq!(actual.policy_version, 1); + assert_eq!(actual.ordinary_limit, 1_000_000_000); + assert_eq!(actual.accepted_snapshots, 0); + assert_eq!(actual.ordinary_used, 1, "the single emission retains its pre-existing ordinary constructor tick"); + assert_eq!(actual.presentation_used, 0); + actual + } + fn assert_failed_report(host: CpuHost, job: JobHandle, actual: crate::job::ProtectedPreviewReport, message: &str) { + assert_eq!(job.protected_preview_report().unwrap(), Some(actual), "no invented zeros or discarded real constructor work"); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Failed); + let error = status.error.unwrap(); + assert_eq!(error.code, ErrorCode::AllocationFailed); + assert_eq!(error.message, message); + assert!(job.frame().unwrap().is_none()); + assert!(job.partial_preview().unwrap().is_none()); + assert!(!job.request_partial_preview().unwrap()); + let request_bytes = job.0._request_reservation.as_ref().map_or(0, |lease| lease.bytes); + assert_eq!(host.admitted_bytes(), request_bytes + 1024, "task/free slots released; actual report metadata retained"); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + #[test] + fn protected_setup_failure_preserves_constructed_task_report_and_error() { + let (host, job, work) = fixture(1); + let observed = std::cell::Cell::new(None); + let running = Running::begin_with_partial_factory(work, |credits| { + // Deterministic fault AFTER the REAL producer and first host slot exist. + observed.set(Some(observed_report(&credits))); + Err(JobError::new(ErrorCode::AllocationFailed, "injected auxiliary setup failure")) + }); + assert!(running.is_none()); + let actual = observed.get().expect("post-construction factory must be reached"); + assert_failed_report(host, job, actual, "injected auxiliary setup failure"); + } + #[test] + fn first_host_slot_failure_preserves_the_raw_producer_report() { + let (host, job, work) = fixture(2); + let Work { scene, handle, reservation, environment, .. } = work; + let plan = handle.0.partial.as_ref().unwrap().protected.unwrap(); + let options = handle.0.request.raytrace.clone().unwrap(); + let task = crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, + handle.0.request.clone(), + handle.0.cancel.clone(), + options, + environment, + handle.0.options.nested_media, + plan, + ) + .unwrap(); + let observed = std::cell::Cell::new(None); + let result = WorkTask::raytrace_with_slot(task, handle.0.partial.as_deref(), |_task| { + // The actual producer exists even though its FIRST wrapper cannot be made. + observed.set(Some(observed_report(handle.0.partial.as_deref().unwrap()))); + Err(JobError::new(ErrorCode::AllocationFailed, "injected first host slot failure")) + }); + let error = result.err().expect("injected wrapping failure must propagate"); + let actual = observed.get().expect("first-slot factory must be reached"); + terminal(&handle, error); + drop(reservation); + drop(handle); + assert_failed_report(host, job, actual, "injected first host slot failure"); + } + #[test] + fn an_actual_constructor_refusal_keeps_report_none_and_skips_auxiliary_setup() { + let (host, job, mut work) = fixture(3); + drop(job); + // Private invalid-constructor fixture only; no public admission/cap bypass. + Arc::get_mut(&mut work.handle.0).unwrap().request.width = 0; + let job = work.handle.clone(); + let running = Running::begin_with_partial_factory(work, |_| panic!("constructor refusal must not attempt auxiliary setup")); + assert!(running.is_none()); + assert!(job.protected_preview_report().unwrap().is_none()); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.frame().unwrap().is_none()); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod directional_shadow_contract { + use super::*; + + // Same queue-only native metadata harness as existing protected setup tests. + // No native worker is spawned; drive the real Running::begin deterministically. + // This checks host queues/leases, not native scheduling qualification. + fn queued_native_host() -> CpuHost { + ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })) + } + + fn capture() -> (ProductScene, ImageRequest) { + let mesh = Mesh { + positions: vec![ + solidcraft_geom::Vec3::new(-10.0, -10.0, 0.0), + solidcraft_geom::Vec3::new(10.0, -10.0, 0.0), + solidcraft_geom::Vec3::new(10.0, 10.0, 0.0), + solidcraft_geom::Vec3::new(-10.0, 10.0, 0.0), + ], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + bounds, + meshes: vec![crate::ProductMesh { + name: "directional glass".into(), + mesh: std::sync::Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + transmission: None, + }], + }; + let mut input = request(); + input.integrator = Integrator::Raytrace; + input.raytrace = Some(super::super::super::RaytraceOptions { + directional_shadow_transmission: true, + dielectrics: vec![super::super::super::DielectricOptions { + body_index: 0, + body_name: "directional glass".into(), + boundary: super::super::super::DielectricBoundary::ThinSheet, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }], + ..Default::default() + }); + (scene, input) + } + + #[test] + fn external_hdr_is_refused_before_admission_or_retained_leases() { + use crate::lighting::{HdrSource, environment_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, 128, 128, 129]); + } + let environment = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap(); + let host = queued_native_host(); + let (scene, input) = capture(); + let error = host.admit_submission(&scene, &input, JobOptions::default(), Some(&environment), None).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(error.message, "directional shadow transmission does not support HDR environments"); + let error = host.submit_with_environment(id(9620, 1), 1, scene, input, Some(environment)).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(error.message, "directional shadow transmission does not support HDR environments"); + assert_eq!(host.admitted_bytes(), 0); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + } + + #[test] + fn cancelled_directional_request_publishes_no_frame_and_releases_work() { + let host = queued_native_host(); + let (scene, input) = capture(); + let retained = input.raytrace.as_ref().unwrap().retained_bytes().unwrap(); + let handle = host.submit(id(9621, 1), 1, scene, input).unwrap(); + assert!(handle.status().unwrap().request.raytrace.as_ref().unwrap().directional_shadow_transmission); + handle.cancel().unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + assert!(Running::begin(work).is_none()); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Cancelled); + assert!(handle.frame().unwrap().is_none()); + assert_eq!(host.admitted_bytes(), retained); + drop(handle); + assert_eq!(host.admitted_bytes(), 0); + } +} + +// Original fixtures for consecutive CPU publication; WRITTEN, NOT RUN. +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod every_cpu_pass { + use super::*; + use crate::job::{CpuBudget, CpuProgressiveOptions, RaytraceOptions}; + + enum Snapshot { + Complete(Arc), + Partial(Arc), + } + impl Snapshot { + fn pass(&self) -> u32 { + match self { + Self::Complete(preview) => preview.info.samples_per_pixel, + Self::Partial(preview) => { + assert_eq!(preview.info.updated_prefix, 0, "automatic publication is a uniform complete pass"); + preview.info.completed_passes + } + } + } + fn png(&self) -> &[u8] { + match self { + Self::Complete(preview) => preview.png(), + Self::Partial(preview) => preview.png(), + } + } + fn sequence(&self) -> u64 { + match self { + Self::Complete(preview) => u64::from(preview.info.frame_sequence), + Self::Partial(preview) => preview.info.sequence, + } + } + } + fn snapshot(job: &JobHandle, protected: bool) -> Option { + if protected { job.partial_preview().unwrap().map(Snapshot::Partial) } else { job.preview().unwrap().map(Snapshot::Complete) } + } + fn fixture(samples: u32, protected: bool) -> (CpuHost, JobHandle, Running) { + let host = ImageHost(Arc::new(Owner { + executor: None, + shared: CpuHost::shared(MEMORY_LIMIT), + kind: HostKind::NativeWorker, + running: Mutex::new(None), + _worker: None, + })); + let request = ImageRequest { + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + budget: if samples > 64 { CpuBudget::Workstation } else { CpuBudget::Compact }, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), + lights: Some(Vec::new()), + ..Default::default() + }), + width: 1, + height: 1, + background: [10, 20, 30], + ..request() + }; + let job = if protected { + host.submit_cpu_protected_partial_with_environment_and_options(id(7790, 1), 19, empty(), request, JobOptions::default(), None) + } else { + host.submit(id(7790, 1), 19, empty(), request) + } + .unwrap(); + let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); + let running = Running::begin(work).unwrap(); + (host, job, running) + } + fn finish(running: &mut Running) { + for _ in 0..10_000_000 { + if !running.advance(16_384).unwrap() { + return; + } + } + panic!("one-pixel every-pass fixture exceeded its finite continuation bound"); + } + fn run_all(samples: u32, protected: bool, quantum: usize) { + let (host, job, mut running) = fixture(samples, protected); + let admission = host.admitted_bytes(); + let mut previous = 0; + let mut complete = false; + for _ in 0..10_000_000 { + let more = running.advance(quantum).unwrap(); + if let Some(preview) = snapshot(&job, protected) { + let pass = preview.pass(); + if pass != previous { + assert_eq!(pass, previous + 1, "no missing, duplicate or reordered complete pass"); + assert!(pass < samples); + match &preview { + Snapshot::Complete(value) => { + assert_eq!(value.info.frame_sequence, pass); + assert_eq!(value.info.frame.job, job.id()); + assert_eq!(value.info.frame.scene_generation, 19); + } + Snapshot::Partial(value) => { + assert_eq!(value.info.sequence, u64::from(pass)); + assert_eq!(value.info.frame.job, job.id()); + assert_eq!(value.info.frame.scene_generation, 19); + assert_eq!(value.covered(), &[0]); + } + } + assert_eq!(image::load_from_memory(preview.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [10, 20, 30, 255]); + assert!(job.frame().unwrap().is_none(), "a provisional pass is not a final image"); + previous = pass; + } + } // No retained consumer Arc and no UI acknowledgement. + assert!(host.admitted_bytes() <= admission, "publication recycles the same two prepaid slots"); + if !more { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(previous, samples - 1); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.cpu_preview_retention_skips, 0); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 })); + assert!(job.preview().unwrap().is_none() && job.partial_preview().unwrap().is_none()); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(image::load_from_memory(frame.png()).unwrap().to_rgba8().get_pixel(0, 0).0, [10, 20, 30, 255]); + if protected { + let report = job.protected_preview_report().unwrap().unwrap(); + assert_eq!(report.accepted_snapshots, samples - 1); + assert_eq!(report.presentation_used, u64::from(samples - 1) * 65_552); + } + drop(frame); + drop(status); + drop(running); + drop(job); + assert_eq!(host.admitted_bytes(), 0); + } + + #[test] + fn real_legacy_and_protected_hosts_publish_every_pass_without_ui_demand() { + for protected in [false, true] { + for quantum in [1, 16_384] { + for samples in [1, 7] { + run_all(samples, protected, quantum); + } + } + } + } + #[test] + #[cfg(target_pointer_width = "64")] + fn real_one_pixel_high_target_crosses_64_with_constant_slots() { + for protected in [false, true] { + run_all(65, protected, 16_384); + } + } + #[test] + fn two_external_snapshots_are_diagnosed_without_waiting_or_losing_the_final() { + for protected in [false, true] { + let (host, job, mut running) = fixture(7, protected); + let mut held = Vec::new(); + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == held.len() as u32 + 1 { + held.push(preview); + } + } + if held.len() == 2 { + break; + } + } + assert_eq!(held.len(), 2); + let hashes: Vec<_> = held.iter().map(|preview| Sha256::digest(preview.png())).collect(); + finish(&mut running); + let status = job.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.cpu_preview_retention_skips, 4, "passes 3,4,5,6 had both slots externally pinned"); + assert!(job.frame().unwrap().is_some()); + for (preview, hash) in held.iter().zip(hashes) { + assert_eq!(Sha256::digest(preview.png()), hash); + } + drop(running); + drop(status); + drop(job); + assert!(host.admitted_bytes() > 0, "external snapshots remain charged after their job drops"); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + #[test] + fn release_after_a_pinned_pass_keeps_publication_sequence_separate_from_actual_spp() { + for protected in [false, true] { + let (host, job, mut running) = fixture(7, protected); + let mut held = Vec::new(); + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == held.len() as u32 + 1 { + held.push(preview); + } + } + if held.len() == 2 { + break; + } + } + assert_eq!(held.len(), 2); + for _ in 0..100_000 { + if job.status().unwrap().cpu_preview_retention_skips == 1 { + break; + } + assert!(running.advance(1).unwrap()); + } + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); + drop(held.remove(0)); // Return exactly one old consumer slot after pass 3. + let mut fourth = None; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == 4 { + fourth = Some(preview); + break; + } + } + } + let fourth = fourth.unwrap(); + assert_eq!(fourth.pass(), 4); + assert_eq!(fourth.sequence(), 3, "SPP 3 was diagnosed, not published"); + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); + drop(fourth); + finish(&mut running); + assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); + assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 1); + drop(running); + drop(job); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + #[test] + fn cancellation_after_third_pass_and_last_digest_chunk_never_publishes_late() { + for protected in [false, true] { + let (host, job, mut running) = fixture(7, protected); + let mut held = None; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = snapshot(&job, protected) { + if preview.pass() == 3 { + held = Some(preview); + break; + } + } + } + let held = held.unwrap(); + let hash = Sha256::digest(held.png()); + for _ in 0..100_000 { + if running.pending_png.is_some() { + break; + } + assert!(running.advance(1).unwrap()); + } + let pending = running.pending_png.as_mut().unwrap(); + while !pending.step(1, &job.0.cancel).unwrap() {} + job.cancel().unwrap(); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); + assert!(job.preview().unwrap().is_none() && job.partial_preview().unwrap().is_none()); + assert!(job.frame().unwrap().is_none()); + assert_eq!(Sha256::digest(held.png()), hash); + drop(running); + drop(job); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + } + #[test] + fn third_checkpoint_is_valid_after_two_but_a_gap_still_fails() { + let (host, job, mut running) = fixture(7, false); + let mut third = None; + for _ in 0..100_000 { + assert!(running.advance(1).unwrap()); + if let Some(preview) = job.preview().unwrap() { + if preview.info.samples_per_pixel == 3 { + third = Some(preview); + break; + } + } + } + let third = third.unwrap(); + assert_eq!(third.info.frame_sequence, 3); + for _ in 0..100_000 { + if running.pending_png.as_ref().is_some_and(|pending| pending.preview_samples == Some(4)) { + break; + } + assert!(running.advance(1).unwrap()); + } + running.pending_png.as_mut().unwrap().preview_samples = Some(5); + assert!(!running.guarded_step(1)); + assert_eq!(job.status().unwrap().progress.phase, Phase::Failed); + assert!(job.preview().unwrap().is_none() && job.frame().unwrap().is_none()); + assert_eq!(third.info.samples_per_pixel, 3); + drop(running); + drop(job); + drop(third); + assert_eq!(host.admitted_bytes(), 0); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/image_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/image_tests.rs new file mode 100644 index 000000000..c8daeae5b --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/image_tests.rs @@ -0,0 +1,915 @@ +use super::*; +use crate::{Camera, ProductMesh, StandardView}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +#[test] +fn raster_ev_scales_lambert_radiance_before_the_existing_single_tone_map() { + let mut part = square("matte", [0; 3], 1.0, Vec3::ZERO); + part.surface = Some(crate::surface::OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()); + let mut alpha = None; + for (ev, expected) in [(-1.0, [69, 77, 77, 255]), (0.0, [94, 104, 104, 255]), (1.0, [124, 135, 135, 255])] { + let mut input = request(); + input.raster_exposure_ev = ev; + input.raster_lights = + Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }]); + let png = finish(ImageTask::new(scene(vec![part.clone()]), input, CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Original analytic oracle: [.4,.5,.5]/pi *2^EV -> Reinhard -> sRGB. + assert_eq!(image.get_pixel(32, 32).0, expected); + assert_eq!(image.get_pixel(0, 0).0, [0; 4]); + let coverage: Vec = image.pixels().map(|pixel| pixel[3]).collect(); + if let Some(expected_alpha) = &alpha { assert_eq!(&coverage, expected_alpha) } else { alpha = Some(coverage) } + } +} + +#[test] +fn raster_ev_covers_implicit_pbr_and_the_weighted_scalar_surrogate_with_original_oracles() { + for (ev, implicit_rgb, weighted_gray) in [(-1.0, [90, 73, 52], 6), (0.0, [120, 99, 73], 12), (1.0, [152, 130, 99], 20)] { + let mut input = request(); + input.raster_exposure_ev = ev; + let mut part = square("matte", [0; 3], 1.0, Vec3::ZERO); + part.surface = Some(crate::surface::OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()); + let png = finish(ImageTask::new(scene(vec![part]), input.clone(), CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Front normal sees only studio Rim:1.5*.6=.9, so rho*.9/pi. + assert_eq!(image.get_pixel(32, 32).0, [implicit_rgb[0], implicit_rgb[1], implicit_rgb[2], 255]); + input.studio_weights = Some([0.0, 0.0, 1.0]); + let png = finish(ImageTask::new(scene(vec![square("scalar", [0; 3], 1.0, Vec3::ZERO)]), input, CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Black roughness1/IOR1.5 surrogate: .28125*F/pi, where the authored + // Schlick approximation F=.04+.96*(1-sqrt(.8))^5. Then2^EV/Reinhard/sRGB. + assert_eq!(image.get_pixel(32, 32).0, [weighted_gray, weighted_gray, weighted_gray, 255]); + } +} + +#[test] +fn raster_ev_legacy_linear_surrogate_preserves_straight_alpha_and_background() { + for (ev, gray) in [(-1.0, 11), (0.0, 19), (1.0, 30)] { + let mut input = request(); + input.raster_exposure_ev = ev; + let part = square("legacy", [0; 3], 0.5, Vec3::ZERO); + let png = finish(ImageTask::new(scene(vec![part.clone()]), input.clone(), CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Front-view scalar shade: spec=.25*(5/6)^20 on already decoded black; + // multiply by2^EV then piecewise sRGB. No Reinhard on this old branch. + assert_eq!(image.get_pixel(32, 32).0, [gray, gray, gray, 128]); + assert_eq!(image.get_pixel(0, 0).0, [0; 4]); + input.transparent_background = false; + let png = finish(ImageTask::new(scene(vec![part]), input, CancelToken::default()).unwrap()); + assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [20, 40, 60, 255]); + } +} + +#[test] +fn raster_ev_zero_wire_is_exact_and_nonfinite_bounds_or_wrong_integrator_refuse() { + let part = scene(vec![square("legacy", [160, 120, 80], 0.5, Vec3::ZERO)]); + let mut input = request(); + let wire = serde_json::to_value(&input).unwrap(); + assert!(wire.get("raster_exposure_ev").is_none()); + let decoded: ImageRequest = serde_json::from_value(wire).unwrap(); + assert_eq!(decoded.raster_exposure_ev, 0.0); + let old = finish(ImageTask::new(part.clone(), input.clone(), CancelToken::default()).unwrap()); + assert_eq!(finish(ImageTask::new(part.clone(), decoded, CancelToken::default()).unwrap()), old); + for zero in [0.0, -0.0] { + input.raster_exposure_ev = zero; + assert_eq!(finish(ImageTask::new(part.clone(), input.clone(), CancelToken::default()).unwrap()), old); + } + for value in [-32.0, 32.0] { + input.raster_exposure_ev = value; + assert!(admit(&part, &input).is_ok()); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -33.0, 33.0] { + input.raster_exposure_ev = value; + assert_eq!(admit(&part, &input).unwrap_err().code, ErrorCode::InvalidRequest); + } + input.raster_exposure_ev = 1.0; + input.integrator = crate::job::Integrator::Raytrace; + assert_eq!(admit(&part, &input).unwrap_err().code, ErrorCode::InvalidRequest); + assert!(crate::job::interactive::cpu_request(&input).is_err()); + #[cfg(feature = "raytrace-cpu")] + { + input.integrator = crate::job::Integrator::Raster; + assert!(crate::raytrace::image::admit(&part, &input, &crate::job::RaytraceOptions::default()).is_err()); + } +} + +fn request() -> ImageRequest { + let mut camera = Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Front); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Default::default(), + raytrace: None, + camera, + width: 64, + height: 64, + background: [20, 40, 60], + transparent_background: true, + } +} + +#[test] +fn render_lights_raster_mute_is_captured_in_request_and_darkens_only_the_product() { + let part = scene(vec![square("part", [200, 180, 160], 1.0, Vec3::ZERO)]); + let mut input = request(); + input.transparent_background = false; + let normal = finish(ImageTask::new(part.clone(), input.clone(), super::CancelToken::default()).unwrap()); + input.studio_weights = Some([0.0; 3]); + let dark = finish(ImageTask::new(part, input, super::CancelToken::default()).unwrap()); + assert_ne!(normal, dark); + let image = image::load_from_memory(&dark).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(32, 32).0, [0, 0, 0, 255]); + assert_eq!(image.get_pixel(0, 0).0, [20, 40, 60, 255]); +} + +fn square(name: &str, colour: [u8; 3], opacity: f64, offset: Vec3) -> ProductMesh { + let mesh = Mesh { + positions: vec![ + Vec3::new(-10.0, 0.0, -10.0) + offset, + Vec3::new(10.0, 0.0, -10.0) + offset, + Vec3::new(10.0, 0.0, 10.0) + offset, + Vec3::new(-10.0, 0.0, 10.0) + offset, + ], + normals: vec![Vec3::new(0.0, -1.0, 0.0); 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 1], + ..Default::default() + }; + ProductMesh { name: name.into(), mesh: Arc::new(mesh), color: colour, opacity, surface: None, transmission: None, faces: Vec::new() } +} + +fn scene(meshes: Vec) -> ProductScene { + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + ProductScene { meshes, bounds } +} + +fn finish(mut task: ImageTask) -> Vec { + for _ in 0..100_000 { + match task.step(4096).unwrap() { + TaskPoll::Complete(png) => return png, + TaskPoll::Pending(p) => assert!(p.done <= p.total, "{p:?}"), + } + } + panic!("bounded fixture did not finish"); +} + +#[test] +fn transparent_png_has_straight_srgb_colour_without_a_shared_edge_seam() { + let scene = scene(vec![square("Glass", [220, 40, 20], 0.5, Vec3::ZERO)]); + let png = finish(ImageTask::new(scene, request(), CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [0; 4]); + for (x, y) in [(32, 32), (31, 31), (30, 32), (32, 30)] { + let p = image.get_pixel(x, y).0; + assert!((i16::from(p[3]) - 128).abs() <= 1, "a shared diagonal must not double-blend: {p:?}"); + assert!(p[0] > 180 && p[0] > p[1] + 60, "RGB is straight, not multiplied by 0.5: {p:?}"); + } + let reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap(); + assert_eq!(reader.info().srgb, Some(png::SrgbRenderingIntent::Perceptual)); +} + +#[test] +fn glass_is_sorted_back_to_front_independently_of_body_order() { + let request = request(); + let far = square("Far", [240, 20, 20], 0.5, request.camera.back() * -5.0); + let near = square("Near", [20, 20, 240], 0.5, request.camera.back() * 5.0); + let a = finish(ImageTask::new(scene(vec![far.clone(), near.clone()]), request.clone(), CancelToken::default()).unwrap()); + let b = finish(ImageTask::new(scene(vec![near, far]), request, CancelToken::default()).unwrap()); + assert_eq!(a, b); + let image = image::load_from_memory(&a).unwrap().to_rgba8(); + let p = image.get_pixel(32, 32).0; + assert!((i16::from(p[3]) - 192).abs() <= 1, "two half-transparent layers: {p:?}"); + assert!(p[2] > p[0] + 30, "the near blue layer contributes more: {p:?}"); +} + +#[test] +fn physical_transmission_keeps_the_exact_scalar_cpu_preview() { + let original = square("Glass", [80, 180, 140], 0.25, Vec3::ZERO); + let mut glass = original.clone(); + glass.surface = Some(crate::surface::OpaqueSurface::new(Vec3::new(0.2, 0.4, 0.3), 0.0, 0.1, 1.5).unwrap()); + glass.transmission = Some(crate::transmission::Transmission::new(Vec3::new(-0.7_f64.ln(), -0.9_f64.ln(), 0.0) / 10.0, None).unwrap()); + let expected = finish(ImageTask::new(scene(vec![original]), request(), CancelToken::default()).unwrap()); + let actual = finish(ImageTask::new(scene(vec![glass]), request(), CancelToken::default()).unwrap()); + assert_eq!(actual, expected); +} + +#[test] +fn cpu_raytrace_refuses_physical_transmission_before_preparation() { + let mut glass = square("Glass", [200; 3], 1.0, Vec3::ZERO); + glass.transmission = Some(crate::transmission::Transmission::new(Vec3::ZERO, Some(1.0)).unwrap()); + let mut input = request(); + input.integrator = super::super::Integrator::Raytrace; + input.transparent_background = false; + let error = admit(&scene(vec![glass]), &input).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert!(error.message.contains("physical transmission")); +} + +#[test] +fn cancellation_is_observed_during_preparation_sort_pixels_and_encoding() { + for stage in [Stage::Looks, Stage::Prepare, Stage::Sort, Stage::Clear, Stage::Glass, Stage::Downsample, Stage::Encode] { + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(vec![square("Glass", [40, 180, 100], 0.4, Vec3::ZERO)]), request(), cancel.clone()).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + if task.stage == stage { + reached = true; + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(reached); + cancel.cancel(); + assert_eq!(task.step(4096).err().unwrap().code, ErrorCode::Cancelled); + } +} + +#[test] +fn encoding_yields_between_rows_and_completed_result_is_consumed_once() { + let mut task = ImageTask::new(scene(Vec::new()), request(), CancelToken::default()).unwrap(); + while task.stage != Stage::Encode { + assert!(matches!(task.step(64).unwrap(), TaskPoll::Pending(_))); + } + let before = task.encoder.as_ref().unwrap().row(); + assert!(matches!(task.step(usize::MAX).unwrap(), TaskPoll::Pending(_))); + assert!(task.encoder.as_ref().unwrap().row() - before <= 4); + loop { + if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() { + assert_eq!(image::load_from_memory(&bytes).unwrap().width(), 64); + break; + } + } + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::NotCompleted); +} + +#[test] +fn invalid_sizes_indices_opacity_and_large_work_lists_fail_without_a_frame() { + let body = square("Product", [100, 120, 140], 1.0, Vec3::ZERO); + let mut bad_request = request(); + bad_request.width = u32::MAX; + assert!(ImageTask::new(scene(vec![body.clone()]), bad_request, CancelToken::default()).is_err()); + for bad in [0, 1] { + let mut body = body.clone(); + if bad == 0 { + Arc::make_mut(&mut body.mesh).triangles[0][0] = u32::MAX; + } else { + body.faces.push(FaceAppearance { face: 0, color: [0; 3], opacity: f64::NAN, surface: None, transmission: None }); + } + let mut task = ImageTask::new(scene(vec![body]), request(), CancelToken::default()).unwrap(); + let error = loop { + if let Err(error) = task.step(64) { + break error; + } + }; + assert_eq!(error.code, ErrorCode::InvalidScene); + } + let mut body = body; + Arc::make_mut(&mut body.mesh).triangles.resize(MAX_TRIANGLES as usize + 1, [0, 1, 2]); + assert_eq!(ImageTask::new(scene(vec![body]), request(), CancelToken::default()).err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(std::mem::size_of::(), 16, "admission accounts for each of the three lists"); +} + +#[test] +fn registered_executor_geometry_admission_excludes_the_cpu_raster_estimate() { + // A library-bounded source: about 100 MiB of face appearances on a small mesh at the + // largest image. Its CPU raster estimate is above 384 MiB at a registered executor's cap. + let count = (100 * 1024 * 1024 / std::mem::size_of::()).min(1_000_000); + let mut body = square("appearances", [200; 3], 1.0, Vec3::ZERO); + body.faces = vec![FaceAppearance { transmission: None, face: 0, color: [200; 3], opacity: 1.0, surface: None }; count]; + let source = scene(vec![body]); + let mut r = request(); + r.width = 2048; + r.height = 2048; + let cpu = admit_raster(admit_source(&source, &r, 1_048_576).unwrap(), &r).unwrap_err(); + assert_eq!(cpu.code, ErrorCode::LimitExceeded); + assert!(cpu.message.contains("384 MiB"), "{}", cpu.message); + let geometry = admit_geometry(&source, &r, 1_048_576).unwrap(); + assert_eq!((geometry.pixel_scratch_bytes, geometry.preparation_bytes), (0, 0)); + assert_eq!(geometry.estimated_total_bytes, geometry.geometry_bytes); + assert_eq!(geometry.face_appearances, count as u64); + // The CPU host itself keeps rejecting the source. + assert_eq!(admit(&source, &r).unwrap_err().code, ErrorCode::LimitExceeded); +} +// Original fixture: a plane at x=40, with exact +X normals. The perspective +// camera looks diagonally from (50/sqrt(2), -50/sqrt(2), 0). Its actual eye is +// on the -X side of this plane, although camera.back has a positive X component. +// The wide field of view keeps the off-axis plane in the image. +fn weighted_matte_view_scene(explicit: bool) -> ProductScene { + let color = [96, 160, 220]; + let mut part = square("weighted matte plane", color, 1.0, Vec3::ZERO); + let mesh = Arc::make_mut(&mut part.mesh); + for p in &mut mesh.positions { + *p = Vec3::new(40.0, p.x + 10.0, p.z); + } + mesh.normals = vec![Vec3::X; 4]; + if explicit { + let [r, g, b] = color.map(decode); + part.surface = Some(crate::surface::OpaqueSurface::new(Vec3::new(r, g, b), 0.0, 1.0, 1.5).unwrap()); + } + scene(vec![part]) +} + +fn weighted_matte_view_request(perspective: bool) -> ImageRequest { + let mut input = request(); + input.camera.yaw = -std::f64::consts::FRAC_PI_4; + input.camera.distance = if perspective { 50.0 } else { 100.0 }; + input.camera.fov = if perspective { 2.4 } else { 0.0 }; + input.transparent_background = false; + // Deliberately not equal: accidentally using light weights instead of + // perspective barycentric weights must not be an equivalent calculation. + input.studio_weights = Some([1.0, 0.35, 0.8]); + input +} + +#[test] +fn weighted_scalar_matte_uses_the_same_perspective_view_as_its_explicit_surface() { + let input = weighted_matte_view_request(true); + assert!(input.camera.back().x > 0.0 && input.camera.eye().x < 40.0); + let scalar = finish(ImageTask::new(weighted_matte_view_scene(false), input.clone(), CancelToken::default()).unwrap()); + let explicit = finish(ImageTask::new(weighted_matte_view_scene(true), input, CancelToken::default()).unwrap()); + // Same admitted geometry, exact unit-axis normals, colour decoder, matte + // response, lights, camera, buffers and encoder. No tolerance or golden. + assert_eq!(scalar, explicit); + let image = image::load_from_memory(&scalar).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [20, 40, 60, 255]); + // Actual view is behind +X everywhere on the plane, so the existing + // one-sided BRDF returns zero. This also proves visible product coverage. + assert!(image.pixels().any(|pixel| pixel.0 == [0, 0, 0, 255])); +} + +#[test] +fn weighted_scalar_matte_keeps_exact_orthographic_surface_equivalence() { + let input = weighted_matte_view_request(false); + let scalar = finish(ImageTask::new(weighted_matte_view_scene(false), input.clone(), CancelToken::default()).unwrap()); + let explicit = finish(ImageTask::new(weighted_matte_view_scene(true), input, CancelToken::default()).unwrap()); + assert_eq!(scalar, explicit); + let image = image::load_from_memory(&scalar).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [20, 40, 60, 255]); + assert!(image.pixels().any(|pixel| pixel.0 != [20, 40, 60, 255] && pixel.0 != [0, 0, 0, 255])); +} + +#[test] +fn weighted_scalar_matte_mute_still_removes_only_product_light() { + let mut input = weighted_matte_view_request(false); + let lit = finish(ImageTask::new(weighted_matte_view_scene(false), input.clone(), CancelToken::default()).unwrap()); + input.studio_weights = Some([0.0; 3]); + let muted = finish(ImageTask::new(weighted_matte_view_scene(false), input, CancelToken::default()).unwrap()); + assert_ne!(lit, muted); + for bytes in [&lit, &muted] { + let image = image::load_from_memory(bytes).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [20, 40, 60, 255]); + } + let image = image::load_from_memory(&muted).unwrap().to_rgba8(); + assert!(image.pixels().any(|pixel| pixel.0 == [0, 0, 0, 255])); +} + +// Original analytic reciprocal-w oracle: the expected surface point is found +// by intersecting a closed-form camera ray with a plane, not by asking either +// raster shading branch to interpolate world coordinates for the other. +#[test] +fn weighted_scalar_perspective_uses_closed_form_ray_plane_world_with_unequal_clip_w() { + let vertices = [Vec3::new(-7.0 / 4.0, -8.0, 7.0 / 4.0), Vec3::new(1.0 / 2.0, -6.0, 7.0 / 2.0), Vec3::new(-3.0, -2.0, -1.0)]; + // The reversed winding faces the eye. This smooth normal is in the + // geometric hemisphere and deliberately separates the three view oracles. + let normal = Vec3::new(3.0, 1.0, 0.0) / 10.0_f64.sqrt(); + let part = ProductMesh { + name: "analytic reciprocal-w matte".into(), + mesh: Arc::new(Mesh { + positions: vertices.to_vec(), + normals: vec![normal; 3], + triangles: vec![[0, 2, 1]], + tri_face: vec![0], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }; + let mut input = request(); + input.width = 4; + input.height = 4; + input.camera = + Camera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.0, roll: 0.0, distance: 10.0, fov: std::f64::consts::FRAC_PI_2, up: crate::UpAxis::Z }; + input.transparent_background = false; + let light_weights = [1.0, 0.35, 0.8]; + input.studio_weights = Some(light_weights); + let mut task = ImageTask::new(scene(vec![part]), input, CancelToken::default()).unwrap(); + assert_eq!((task.sw, task.sh), (8, 8)); + let eye = Vec3::new(0.0, -10.0, 0.0); + let back = Vec3::new(0.0, -1.0, 0.0); + assert_eq!(task.request.camera.eye(), eye); + assert_eq!(task.back, back); + + // Actual production projection of [A,C,B], not a hand-filled Triangle. + // With tan(fov/2)=1, clip w is depth from the eye: [2,8,4]. + let projected = task.project(Draw::default()).unwrap().unwrap(); + assert!(projected.surface.is_none()); + let expected_points = [[0.5, 0.5], [2.5, 4.5], [4.5, 0.5]]; + for ((actual, expected), (actual_inv_w, expected_inv_w)) in + projected.points.iter().zip(expected_points).zip(projected.inv_w.iter().zip([0.5, 0.125, 0.25])) + { + assert!((actual[0] - expected[0]).abs() < 1e-12); + assert!((actual[1] - expected[1]).abs() < 1e-12); + assert!((*actual_inv_w - expected_inv_w).abs() < 1e-12); + } + assert_eq!(projected.world, [vertices[0], vertices[2], vertices[1]]); + + // Pixel sample (2.5,2.5) gives the analytic forward ray + // E + t*(-3/8,1,3/8). The triangle plane is 4x-y-4z=-6: + // plane(E)=10 and plane(ray)=-4, hence t=4 exactly. + let plane = Vec3::new(4.0, -1.0, -4.0); + assert_eq!((vertices[2] - vertices[0]).cross(vertices[1] - vertices[0]), plane * 4.0); + assert!(normal.dot(plane) > 0.0); + for vertex in vertices { + assert_eq!(plane.dot(vertex), -6.0); + } + let ray = Vec3::new(-3.0 / 8.0, 1.0, 3.0 / 8.0); + assert_eq!(plane.dot(eye), 10.0); + assert_eq!(plane.dot(ray), -4.0); + let expected_world = Vec3::new(-3.0 / 2.0, -6.0, 3.0 / 2.0); + assert_eq!(eye + ray * 4.0, expected_world); + let expected_view = Vec3::new(3.0 / 2.0, -4.0, -3.0 / 2.0); + assert_eq!(eye - expected_world, expected_view); + // Screen barycentrics [1/4,1/2,1/4] and clip w [2,8,4] + // imply world barycentrics [1/2,1/4,1/4]. An AFFINE world + // would instead be (-29/16,-9/2,13/16), a different camera ray. + let affine_world = Vec3::new(-29.0 / 16.0, -9.0 / 2.0, 13.0 / 16.0); + let affine_view = eye - affine_world; + assert!((normal.dot(expected_view) - 1.0 / (2.0 * 10.0_f64.sqrt())).abs() < 1e-14); + assert!((normal.dot(affine_view) + 1.0 / (16.0 * 10.0_f64.sqrt())).abs() < 1e-14); + assert!(normal.dot(back) < 0.0); + + // Black base removes diffuse but retains dielectric Fresnel. Only the + // key light is above this normal. For roughness=1, D=1/pi and Smith + // visibility reduces to 1/((1+nv)*(1+nl)). F0=(1/5)^2. + let nv = 1.0 / 820.0_f64.sqrt(); + let nl = 9.0 / (5.0 * 10.0_f64.sqrt()); + let vh = ((1.0 - 3.0 / (5.0 * 82.0_f64.sqrt())) / 2.0).sqrt(); + let fresnel = 1.0 / 25.0 + (24.0 / 25.0) * (1.0 - vh).powi(5); + let expected_radiance = 3.0 * nl * fresnel / (std::f64::consts::PI * (1.0 + nv) * (1.0 + nl)); + let matte = crate::surface::OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.5).unwrap(); + let reference = crate::studio::shade_weighted(matte, normal, expected_view, light_weights).unwrap(); + assert!((reference - Vec3::new(expected_radiance, expected_radiance, expected_radiance)).len() < 1e-14); + assert_eq!(crate::studio::shade_weighted(matte, normal, affine_view, light_weights).unwrap(), Vec3::ZERO); + assert_eq!(crate::studio::shade_weighted(matte, normal, back, light_weights).unwrap(), Vec3::ZERO); + + // The original radical expression gives radiance0.0144120124528... + // Reinhard then sRGB yields31.6843707068... on the8-bit scale, hence32. + // Inspect the real production supersample before downsampling; no fake + // renderer, injected pixel, shared-branch PNG equality or golden is used. + for _ in 0..2048 { + if task.stage == Stage::Downsample { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(task.stage == Stage::Downsample); + let sample = 2 * task.sw + 2; + assert!(task.depth[sample].is_finite(), "the analytic sample must be covered"); + assert_eq!(task.pixels[sample], [32, 32, 32, 255]); + // Finish through the ordinary encoder as well; the unoccupied corner + // remains the original opaque background. + let png = finish(task); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!((image.width(), image.height()), (4, 4)); + assert_eq!(image.get_pixel(3, 3).0, [20, 40, 60, 255]); +} + +#[test] +fn explicit_raster_linear_rgb_reaches_png_with_one_display_transfer() { + let mut part = square("matte", [0; 3], 1.0, Vec3::ZERO); + part.surface = Some(crate::surface::OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()); + let mut input = request(); + // Orthographic Front is exactly normal to the square, so no perspective-view approximation. + assert_eq!(input.camera.fov, 0.0); + input.raster_lights = Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }]); + let png = finish(ImageTask::new(scene(vec![part]), input, CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Independently derived: [.4,.5,.5]/pi -> Reinhard -> piecewise sRGB -> nearest byte. + for (x, y) in [(32, 32), (31, 32), (32, 31)] { + assert_eq!(image.get_pixel(x, y).0, [94, 104, 104, 255]); + } + assert_eq!(image.get_pixel(0, 0).0, [0; 4]); +} + +#[test] +fn explicit_raster_three_four_five_cosine_reaches_png() { + let mut part = square("matte", [0; 3], 1.0, Vec3::ZERO); + part.surface = Some(crate::surface::OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()); + let mut input = request(); + input.raster_lights = Some(vec![crate::job::DirectionalLightOptions { direction: [3.0, -4.0, 0.0], color: [1.0; 3], intensity: 2.0 }]); + let png = finish(ImageTask::new(scene(vec![part]), input, CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Independently derived: [1.28,.8,.4]/pi -> Reinhard -> sRGB. + assert_eq!(image.get_pixel(32, 32).0, [146, 124, 94, 255]); +} + +#[test] +fn explicit_empty_raster_rig_is_dark_while_absence_keeps_legacy() { + let part = scene(vec![square("part", [200, 180, 160], 1.0, Vec3::ZERO)]); + let mut input = request(); + input.transparent_background = false; + let absent = finish(ImageTask::new(part.clone(), input.clone(), CancelToken::default()).unwrap()); + let wire = serde_json::to_value(&input).unwrap(); + assert!(wire.get("raster_lights").is_none()); + let mut null = wire.clone(); + null["raster_lights"] = serde_json::Value::Null; + let legacy: ImageRequest = serde_json::from_value(null).unwrap(); + assert_eq!(finish(ImageTask::new(part.clone(), legacy, CancelToken::default()).unwrap()), absent); + input.raster_lights = Some(Vec::new()); + let dark = finish(ImageTask::new(part, input, CancelToken::default()).unwrap()); + assert_ne!(dark, absent); + let image = image::load_from_memory(&dark).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(32, 32).0, [0, 0, 0, 255]); + assert_eq!(image.get_pixel(0, 0).0, [20, 40, 60, 255]); +} + +#[test] +fn explicit_raster_request_rejects_capacity_conflicts_and_foreign_integrators() { + let part = scene(vec![square("part", [200; 3], 1.0, Vec3::ZERO)]); + let light = crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 1.0 }; + let mut input = request(); + let mut oversized = Vec::with_capacity(9); + oversized.push(light); + input.raster_lights = Some(oversized); + assert_eq!(admit(&part, &input).unwrap_err().code, ErrorCode::InvalidRequest); + input.raster_lights = Some(Vec::new()); + input.studio_weights = Some([1.0; 3]); + assert_eq!(admit(&part, &input).unwrap_err().code, ErrorCode::InvalidRequest); + input.studio_weights = None; + input.raytrace = Some(Default::default()); + assert_eq!(admit(&part, &input).unwrap_err().code, ErrorCode::InvalidRequest); + input.raytrace = None; + input.integrator = crate::job::Integrator::Raytrace; + assert_eq!(admit(&part, &input).unwrap_err().code, ErrorCode::InvalidRequest); +} + +#[test] +fn explicit_raster_scalar_surrogate_preserves_straight_alpha_without_claiming_glass() { + let part = square("scalar", [0; 3], 0.5, Vec3::ZERO); + let mut input = request(); + input.raster_lights = Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 2.0 }]); + let png = finish(ImageTask::new(scene(vec![part.clone()]), input.clone(), CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + // Scalar surrogate rho=0, IOR=1.5, roughness=1: F0/4pi=.01/pi. + // Intensity2 gives .02/pi; Reinhard + sRGB independently rounds to19. + assert_eq!(image.get_pixel(32, 32).0, [19, 19, 19, 128]); + let mut physical = part; + physical.transmission = Some(crate::transmission::Transmission::new(Vec3::ZERO, None).unwrap()); + assert_eq!(admit(&scene(vec![physical]), &input).unwrap_err().code, ErrorCode::InvalidRequest); +} +#[test] +fn direct_raster_task_accounts_empty_rig_capacity_without_changing_dark_or_legacy_paths() { + let part = scene(vec![square("part", [200; 3], 1.0, Vec3::ZERO)]); + let legacy = request(); + let legacy_bytes = admit(&part, &legacy).unwrap().estimated_total_bytes; + assert!(ImageTask::new(part.clone(), legacy, CancelToken::default()).unwrap().request.raster_lights.is_none()); + let fee = (8 * std::mem::size_of::()) as u64; + let mut dark_png = None; + for capacity in [0, 8] { + let mut input = request(); + input.raster_lights = Some(Vec::with_capacity(capacity)); + let retained_capacity = input.raster_lights.as_ref().unwrap().capacity(); + assert!(retained_capacity >= capacity && retained_capacity <= 8); + let actual_bytes = (retained_capacity * std::mem::size_of::()) as u64; + let admitted = admit(&part, &input).unwrap(); + assert_eq!(admitted.estimated_total_bytes, legacy_bytes + fee); + assert!(admitted.estimated_total_bytes - legacy_bytes >= actual_bytes); + // This is the public direct constructor, not host try_copy/Record fees. + let task = ImageTask::new(part.clone(), input, CancelToken::default()).unwrap(); + assert_eq!(task.request.raster_lights.as_ref().unwrap().capacity(), retained_capacity); + assert_eq!(task.admission.estimated_total_bytes, legacy_bytes + fee); + let png = finish(task); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(32, 32).0, [0, 0, 0, 255]); + if let Some(expected) = &dark_png { + assert_eq!(&png, expected); + } else { + dark_png = Some(png); + } + } +} + +fn raster_local_triangle() -> Triangle { + let surface = crate::surface::OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap(); + Triangle { + points: [[-1.0, -1.0, 0.5], [3.0, -1.0, 0.5], [-1.0, 3.0, 0.5]], + world: [Vec3::new(-1.0, 0.0, 1.0), Vec3::new(3.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, -3.0)], + normals: [-Vec3::Y; 3], + inv_w: [1.0; 3], + colour: [0.0; 3], + opacity: 1.0, + surface: Some(surface), + centre_depth: 0.0, + area: 16.0, + bounds: [0, 0, 0, 0], + x: 0, + y: 0, + } +} + +fn raster_local_point() -> crate::job::PunctualLightOptions { + crate::job::PunctualLightOptions { + position_mm: [0.5, -10.0, -0.5], + color: [0.25, 0.5, 1.0], + intensity: 2.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + } +} + +fn raster_local_area() -> crate::job::RectangleLightOptions { + crate::job::RectangleLightOptions { + center_mm: [0.5, -10.0, -0.5], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, 0.0, -2.0], + color: [0.25, 0.5, 1.0], + intensity: 2.0, + } +} + +fn raster_local_pixel(triangle: &Triangle, input: &ImageRequest) -> [u8; 4] { + let mut pixels = [[0; 4]]; + let mut depth = [f32::INFINITY]; + raster_pixel(triangle, 1, -Vec3::Y, None, input, &mut pixels, &mut depth).unwrap(); + pixels[0] +} + +fn raster_local_expected(numerators: [f64; 3]) -> [u8; 4] { + let rgb = numerators.map(|n| { + let linear = n / std::f64::consts::PI; + solidcraft_geom::srgb::encode8(linear / (1.0 + linear)) + }); + [rgb[0], rgb[1], rgb[2], 255] +} + +#[test] +fn raster_local_point_pixel_matches_independent_lambert_and_single_exposure_oracles() { + // Affine barycentrics (1/4,3/8,3/8) put this sample at(.5,0,-.5). + // Point is10mm along the normal, at its10mm reference: RGB*rho*I/pi. + let mut input = request(); + input.raster_punctual_lights = Some(vec![raster_local_point()]); + for (ev, expected) in [(-1.0, [69, 77, 77, 255]), (0.0, [94, 104, 104, 255]), (1.0, [124, 135, 135, 255])] { + input.raster_exposure_ev = ev; + assert_eq!(raster_local_pixel(&raster_local_triangle(), &input), expected); + } + input.raster_exposure_ev = 0.0; + input.raster_punctual_lights.as_mut().unwrap()[0].position_mm[1] = -20.0; + assert_eq!(raster_local_pixel(&raster_local_triangle(), &input), raster_local_expected([0.1, 0.125, 0.125])); +} + +#[test] +fn raster_local_spot_area_and_mixed_pixels_have_original_closed_form_contributions() { + let mut point = raster_local_point(); + point.cone = Some(crate::job::SpotConeOptions { + emitted_axis: [3.0_f64.sqrt(), 1.0, 0.0], + inner_half_angle_radians: 0.8_f64.acos(), + outer_half_angle_radians: 0.2_f64.acos(), + }); + let mut input = request(); + input.raster_punctual_lights = Some(vec![point]); + // Axis cosine1/2 lies halfway between(4/5,1/5), so smoothstep=1/2. + assert_eq!(raster_local_pixel(&raster_local_triangle(), &input), raster_local_expected([0.2, 0.25, 0.25])); + input.raster_punctual_lights = None; + input.raster_area_lights = Some(vec![raster_local_area()]); + // Area4 * I2 / r^2(100) =.08 before rho*colour/pi. + assert_eq!(raster_local_pixel(&raster_local_triangle(), &input), raster_local_expected([0.016, 0.02, 0.02])); + input.raster_lights = Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 1.0 }]); + input.raster_punctual_lights = Some(vec![raster_local_point()]); + assert_eq!(raster_local_pixel(&raster_local_triangle(), &input), raster_local_expected([1.216, 1.02, 0.77])); + input.raster_lights = None; + input.raster_punctual_lights = None; + input.raster_area_lights.as_mut().unwrap()[0].edge_v_mm = [0.0, 0.0, 2.0]; + assert_eq!(raster_local_pixel(&raster_local_triangle(), &input), [0, 0, 0, 255]); +} + +#[test] +fn raster_local_pixel_uses_reciprocal_w_world_position_and_zero_coincidence_policy() { + let mut triangle = raster_local_triangle(); + triangle.inv_w = [1.0, 2.0, 8.0]; + // Weighted world=(-1/4,0,-2), not the affine(.5,0,-.5). + let mut point = raster_local_point(); + point.position_mm = [-0.25, -1.0, -2.0]; + point.reference_distance_mm = 1.0; + point.color = [1.0; 3]; + let mut input = request(); + input.raster_punctual_lights = Some(vec![point]); + assert_eq!(raster_local_pixel(&triangle, &input), raster_local_expected([1.6, 1.0, 0.5])); + input.raster_punctual_lights.as_mut().unwrap()[0].position_mm = [-0.25, 0.0, -2.0]; + assert_eq!(raster_local_pixel(&triangle, &input), [0, 0, 0, 255]); +} + +#[test] +fn raster_local_real_task_empty_rig_is_dark_and_null_keeps_exact_legacy_png() { + let part = scene(vec![square("opaque", [200, 180, 160], 1.0, Vec3::ZERO)]); + let mut input = request(); + input.transparent_background = false; + let legacy = finish(ImageTask::new(part.clone(), input.clone(), CancelToken::default()).unwrap()); + let mut wire = serde_json::to_value(&input).unwrap(); + wire["raster_punctual_lights"] = serde_json::Value::Null; + wire["raster_area_lights"] = serde_json::Value::Null; + let decoded: ImageRequest = serde_json::from_value(wire).unwrap(); + assert_eq!(finish(ImageTask::new(part.clone(), decoded, CancelToken::default()).unwrap()), legacy); + for family in [0, 1] { + let mut explicit = input.clone(); + if family == 0 { + explicit.raster_punctual_lights = Some(Vec::new()); + } else { + explicit.raster_area_lights = Some(Vec::new()); + } + let png = finish(ImageTask::new(part.clone(), explicit, CancelToken::default()).unwrap()); + let image = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(32, 32).0, [0, 0, 0, 255]); + assert_eq!(image.get_pixel(0, 0).0, [20, 40, 60, 255]); + assert_ne!(png, legacy); + } +} + +#[test] +fn raster_local_real_task_admits_spare_capacity_and_refuses_physical_transmission() { + let part = scene(vec![square("opaque", [200; 3], 1.0, Vec3::ZERO)]); + let mut input = request(); + let legacy_bytes = admit(&part, &input).unwrap().estimated_total_bytes; + input.raster_punctual_lights = Some(Vec::with_capacity(8)); + input.raster_area_lights = Some(Vec::with_capacity(4)); + let fee = (8 * std::mem::size_of::() + 4 * std::mem::size_of::()) as u64; + assert_eq!(admit(&part, &input).unwrap().estimated_total_bytes, legacy_bytes + fee); + let capacities = (input.raster_punctual_lights.as_ref().unwrap().capacity(), input.raster_area_lights.as_ref().unwrap().capacity()); + let task = ImageTask::new(part, input, CancelToken::default()).unwrap(); + assert_eq!(task.request.raster_punctual_lights.as_ref().unwrap().capacity(), capacities.0); + assert_eq!(task.request.raster_area_lights.as_ref().unwrap().capacity(), capacities.1); + assert_eq!(task.admission.estimated_total_bytes, legacy_bytes + fee); + let mut physical = square("physical", [200; 3], 1.0, Vec3::ZERO); + physical.transmission = Some(crate::transmission::Transmission::new(Vec3::ZERO, None).unwrap()); + assert_eq!(admit(&scene(vec![physical]), &task.request).unwrap_err().code, ErrorCode::InvalidRequest); +} + +#[test] +fn raster_local_light_work_remains_inside_original_cap_and_step_cancellation() { + let part = scene(vec![square("opaque", [200; 3], 1.0, Vec3::ZERO)]); + let mut legacy = request(); + legacy.raster_lights = Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 1.0 }]); + let mut local = legacy.clone(); + local.raster_punctual_lights = Some(vec![raster_local_point()]); + local.raster_area_lights = Some(vec![raster_local_area()]); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(part.clone(), local, cancel.clone()).unwrap(); + let triangle = task.project(Draw { body: 0, triangle: 0, depth: 0.0 }).unwrap().unwrap(); + let [x0, x1, y0, y1] = triangle.bounds; + let pixels = ((x1 - x0 + 1) * (y1 - y0 + 1)) as u64; + task.pixel_tests = MAX_PIXEL_TESTS - pixels * 3 + 1; + assert_eq!(task.prepare_step().unwrap_err().code, ErrorCode::LimitExceeded); + let mut old_task = ImageTask::new(part, legacy, CancelToken::default()).unwrap(); + old_task.pixel_tests = MAX_PIXEL_TESTS - pixels * 3 + 1; + old_task.prepare_step().unwrap(); + assert_eq!(old_task.pixel_tests, MAX_PIXEL_TESTS - pixels * 2 + 1, "directional-only budget is unchanged"); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); +} + +#[test] +fn raster_local_running_progress_counts_pixel_visits_and_reaches_total_before_encoding() { + // Cost is1 for unchanged implicit/directional-only routes,3 for the minimal + // mixed rig and20 for8D+8 shared point/spot+4area. Progress counts actual + // clear/draw/downsample visits, never BRDF evaluations or light intensity. + for (factor, directional_count, punctual_count, area_count) in [(1u64, 0usize, 0usize, 0usize), (1, 1, 0, 0), (3, 1, 1, 1), (20, 8, 8, 4)] { + let mut input = request(); + input.width = 8; + input.height = 8; + if directional_count > 0 { + input.raster_lights = + Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 1.0 }; directional_count]); + } + if punctual_count > 0 { + let mut points = vec![raster_local_point(); punctual_count]; + points[punctual_count - 1].cone = + Some(crate::job::SpotConeOptions { emitted_axis: [0.0, 1.0, 0.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); + input.raster_punctual_lights = Some(points); + } + if area_count > 0 { + input.raster_area_lights = Some(vec![raster_local_area(); area_count]); + } + let back = input.camera.back(); + let part = scene(vec![ + square("opaque", [160; 3], 1.0, Vec3::ZERO), + square("alpha far", [160; 3], 0.5, back * -5.0), + square("alpha nearer", [160; 3], 0.5, back * -3.0), + ]); + let mut task = ImageTask::new(part, input, CancelToken::default()).unwrap(); + for _ in 0..100_000 { + if task.stage == Stage::Clear { + break; + } + assert!(matches!(task.stage, Stage::Looks | Stage::Prepare | Stage::Sort)); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(task.stage == Stage::Clear, "bounded fixture must finish preparation"); + let mut bbox_visits = 0u64; + for draw in task.opaque.iter().chain(&task.glass) { + let triangle = task.project(*draw).unwrap().unwrap(); + let [x0, x1, y0, y1] = triangle.bounds; + bbox_visits += ((x1 - x0 + 1) * (y1 - y0 + 1)) as u64; + } + assert!(bbox_visits > 0); + assert_eq!(task.pixel_tests, bbox_visits * factor, "weighted128M work guard remains authoritative"); + let clear_visits = (task.sw * task.sh) as u64; + let output_visits = u64::from(task.request.width) * u64::from(task.request.height); + let expected_total = clear_visits + bbox_visits + output_visits; + let mut last_done = 0; + let mut saw_opaque = false; + let mut saw_downsample = false; + let mut saw_running_complete = false; + for _ in 0..100_000 { + if task.stage == Stage::Encode { + break; + } + let progress = task.progress(); + assert_eq!(progress.phase, Phase::Running); + assert_eq!(progress.total, expected_total, "total must not scale with {factor} lights"); + assert!(progress.done >= last_done && progress.done <= progress.total); + if !saw_opaque && task.stage == Stage::Opaque { + assert_eq!(progress.done, clear_visits, "clear units unchanged"); + saw_opaque = true; + } + if !saw_downsample && task.stage == Stage::Downsample { + assert_eq!(progress.done, clear_visits + bbox_visits, "every projected visit completed before downsample"); + saw_downsample = true; + } + if progress.done == progress.total { + saw_running_complete = true; + } + last_done = progress.done; + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(task.stage == Stage::Encode); + assert!(saw_opaque && saw_downsample && saw_running_complete, "Running must reach its boundary before Encoding"); + assert_eq!(last_done, expected_total); + assert_eq!(task.pixel_done, expected_total); + assert_eq!(task.progress().phase, Phase::Encoding); + let png = finish(task); + assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (8, 8)); + } +} + +#[test] +fn captured_cpu_preview_cadence_roundtrips_without_saved_sampling_or_nested_aliases() { + let mut input = request(); + input.integrator = super::super::Integrator::Raytrace; + input.transparent_background = false; + input.raytrace = Some(super::super::RaytraceOptions { + progressive: Some(super::super::CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 }), + ..Default::default() + }); + for every_pass in [true, false] { + input.cpu_progressive_every_pass = every_pass; + let wire = serde_json::to_value(&input).unwrap(); + assert_eq!(wire.get("cpu_progressive_every_pass"), (!every_pass).then_some(&serde_json::Value::Bool(false))); + assert!(wire["raytrace"].get("cpu_progressive_every_pass").is_none()); + let decoded: ImageRequest = serde_json::from_value(wire).unwrap(); + assert_eq!(decoded.cpu_progressive_every_pass, every_pass); + assert_eq!(decoded.raytrace.as_ref().unwrap().progressive, input.raytrace.as_ref().unwrap().progressive); + assert_eq!(decoded.try_clone_for_host().unwrap().cpu_progressive_every_pass, every_pass); + } +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn legacy_protected_feedback_restores_the_original_global_distribution_and_sixty_four_cap() { + use super::super::{CpuBudget, ProtectedPreviewPlan}; + let tiny = ProtectedPreviewPlan::with_cadence(2, 1, 5, CpuBudget::Compact, false).unwrap(); + assert_eq!(tiny.quota_limit(), 9); + assert_eq!((0..9).map(|index| tiny.milestone(index).unwrap()).collect::>(), [1, 2, 3, 4, 5, 6, 7, 8, 9]); + let plan = ProtectedPreviewPlan::with_cadence(65, 1, 3, CpuBudget::Compact, false).unwrap(); + plan.validate().unwrap(); + assert_eq!(plan.quota_limit(), 64); + assert_eq!([0, 1, 31, 32, 63].map(|index| plan.milestone(index).unwrap()), [1, 4, 95, 99, 194]); + let milestones: Vec<_> = (0..64).map(|index| plan.milestone(index).unwrap()).collect(); + for committed in 0..=195 { + let expected = milestones.iter().filter(|&&milestone| milestone <= committed).count() as u32; + assert_eq!(plan.reached_milestones(committed).unwrap(), expected); + } + assert!(plan.reached_milestones(196).is_err()); + assert!(plan.milestone(64).is_err()); + assert_eq!(plan.presentation_limit().unwrap(), 64 * plan.snapshot_work().unwrap()); + assert_eq!(plan.ordinary_limit(), CpuBudget::Compact.limits().max_work_units); + let single = ProtectedPreviewPlan::with_cadence(1, 1, 1, CpuBudget::Compact, false).unwrap(); + assert_eq!((single.quota_limit(), single.reached_milestones(1).unwrap()), (0, 0)); + let one = ProtectedPreviewPlan::with_cadence(1, 1, 2, CpuBudget::Compact, false).unwrap(); + assert_eq!((one.quota_limit(), one.milestone(0).unwrap(), one.reached_milestones(1).unwrap()), (1, 1, 1)); + let high = ProtectedPreviewPlan::with_cadence(1, 1, 1_048_576, CpuBudget::Workstation, false).unwrap(); + assert_eq!((high.quota_limit(), high.milestone(63).unwrap()), (64, 1_048_575)); + assert_eq!(high.reached_milestones(1_048_576).unwrap(), 64); + let current = ProtectedPreviewPlan::new(65, 1, 3, CpuBudget::Compact).unwrap(); + assert_eq!(current.quota_limit(), 66); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/led_strip/tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/led_strip/tests.rs new file mode 100644 index 000000000..55c8940ae --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/led_strip/tests.rs @@ -0,0 +1,259 @@ +use super::*; + +fn strip() -> LedStripOptions { + LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + } +} + +#[test] +fn dimensions_and_orientation_lower_without_power_multiplier() { + let rectangle = strip().rectangle().unwrap(); + assert_eq!(rectangle.edge_u_mm, [8.0, 0.0, 0.0]); + assert_eq!(rectangle.edge_v_mm, [0.0, -0.5, 0.0]); + assert_eq!(rectangle.intensity, 2.0); + assert_eq!(rectangle.color, [1.0, 0.5, 0.25]); +} + +#[test] +fn rejects_hostile_geometry_radiance_and_unsupported_pitch() { + for bad in [f64::NAN, f64::INFINITY, -1.0, 0.0, 1e-7, 1e6 + 1.0] { + assert!(LedStripOptions { length_mm: bad, ..strip() }.rectangle().is_err()); + assert!(LedStripOptions { width_mm: bad, ..strip() }.rectangle().is_err()); + } + for axis in [[0.0; 3], [2.0, 0.0, 0.0], [f64::NAN, 0.0, 0.0], [0.0, -1.0, 0.0]] { + assert!(LedStripOptions { length_axis: axis, ..strip() }.rectangle().is_err()); + } + assert!(LedStripOptions { center_mm: [1e12, 0.0, 0.0], ..strip() }.rectangle().is_err()); + assert!(LedStripOptions { color: [1.01, 0.0, 0.0], ..strip() }.rectangle().is_err()); + assert!(LedStripOptions { intensity: 65.0, ..strip() }.rectangle().is_err()); + let mut wire = serde_json::to_value(strip()).unwrap(); + wire["pitch_mm"] = serde_json::json!(10); + assert!(serde_json::from_value::(wire).is_err()); +} + +#[test] +fn one_slot_per_strip_and_original_capacity_accounted() { + let mut options = RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }; + for count in 1..=4 { + strip().append_to(&mut options, 64).unwrap(); + assert_eq!(options.area_lights.as_ref().unwrap().len(), count); + assert_eq!(options.area_samples, Some(64)); + assert_eq!( + options.retained_bytes().unwrap(), + (options.area_lights.as_ref().unwrap().capacity() * std::mem::size_of::()) as u64 + ); + options.validate().unwrap(); + } + let original = options.clone(); + assert!(strip().append_to(&mut options, 64).is_err()); + assert_eq!(options, original); +} + +#[test] +fn rejection_is_atomic_including_capacity_and_conflicting_sample_count() { + let mut options = RaytraceOptions::default(); + strip().append_to(&mut options, 16).unwrap(); + for (input, samples) in [(strip(), 4), (strip(), 3), (LedStripOptions { width_mm: 0.0, ..strip() }, 16)] { + let before = options.clone(); + let capacity = options.area_lights.as_ref().unwrap().capacity(); + assert!(input.append_to(&mut options, samples).is_err()); + assert_eq!(options, before); + assert_eq!(options.area_lights.as_ref().unwrap().capacity(), capacity); + } + let mut over = RaytraceOptions { area_lights: Some(Vec::with_capacity(5)), ..Default::default() }; + assert!(strip().append_to(&mut over, 1).is_err()); + assert_eq!(over.area_lights.as_ref().unwrap().capacity(), 5); +} + +#[test] +fn final_edge_cosine_rejection_preserves_request_and_capacity() { + let a = 1.0 - 5e-13; + let input = LedStripOptions { length_axis: [a, 0.0, 0.0], width_axis: [1e-10, a, 0.0], ..strip() }; + assert!(input.rectangle().is_err()); + let mut options = RaytraceOptions::default(); + strip().append_to(&mut options, 16).unwrap(); + let before = options.clone(); + let capacity = options.area_lights.as_ref().unwrap().capacity(); + assert!(input.append_to(&mut options, 16).is_err()); + assert_eq!(options, before); + assert_eq!(options.area_lights.as_ref().unwrap().capacity(), capacity); + options.validate().unwrap(); +} + +#[test] +fn rounded_dimension_endpoints_never_return_rt3_invalid_edges() { + let k = 0.5_f64.sqrt(); + for dimension in [1e-6_f64.next_down(), 1e-6, 1e-6_f64.next_up(), 1e6_f64.next_down(), 1e6, 1e6_f64.next_up()] { + for (u, v) in [([1.0, 0.0, 0.0], [0.0, -1.0, 0.0]), ([k, k, 0.0], [k, -k, 0.0])] { + let input = LedStripOptions { length_mm: dimension, width_mm: dimension, length_axis: u, width_axis: v, ..strip() }; + let mut options = RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }; + if let Ok(rectangle) = input.rectangle() { + options.area_lights = Some(vec![rectangle]); + options.validate().unwrap(); + let mut lowered = RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }; + input.append_to(&mut lowered, 1).unwrap(); + lowered.validate().unwrap(); + } else { + let before = options.clone(); + assert!(input.append_to(&mut options, 1).is_err()); + assert_eq!(options, before); + } + } + } + for dimension in [1e-6, 1e6] { + LedStripOptions { length_mm: dimension, width_mm: dimension, ..strip() }.rectangle().unwrap(); + } +} + +#[test] +fn recipe_roundtrip_and_tints_are_explicit_linear_values() { + assert_eq!(serde_json::from_value::(serde_json::to_value(strip()).unwrap()).unwrap(), strip()); + assert_eq!(StripTint::Red.linear_rgb(), [1.0, 0.0, 0.0]); + assert_eq!(StripTint::Green.linear_rgb(), [0.0, 1.0, 0.0]); + assert_eq!(StripTint::Blue.linear_rgb(), [0.0, 0.0, 1.0]); + assert!(StripTint::Warm.linear_rgb()[0] > StripTint::Warm.linear_rgb()[2]); + assert!(StripTint::Cool.linear_rgb()[2] > StripTint::Cool.linear_rgb()[0]); +} + +#[cfg(feature = "raytrace-cpu")] +mod consumer { + use super::*; + use crate::job::{CancelToken, ImageRequest, Integrator, TaskPoll}; + use crate::raytrace::{area::RectangleLight, image::ImageTask}; + use crate::{Camera, ProductMesh, ProductScene, StandardView, surface::OpaqueSurface}; + use solidcraft_geom::{Aabb3, Mesh}; + use std::sync::Arc; + + fn light(input: LedStripOptions) -> RectangleLight { + let r = input.rectangle().unwrap(); + let vec = |[x, y, z]: [f64; 3]| Vec3::new(x, y, z); + RectangleLight::new(vec(r.center_mm), vec(r.edge_u_mm), vec(r.edge_v_mm), vec(r.color), r.intensity).unwrap() + } + + #[test] + fn analytic_area_weight_inverse_square_and_orientation() { + let source = light(strip()); + assert_eq!(source.area_mm2(), 4.0); + assert_eq!(source.normal(), -Vec3::Z); + let sample = source.sample(Vec3::ZERO, 0, 0, 0, 1, 0).unwrap().unwrap(); + assert!((sample.incident() - Vec3::new(0.08, 0.04, 0.02)).len() < 1e-14); + let far = light(LedStripOptions { center_mm: [0.0, 0.0, 20.0], ..strip() }).sample(Vec3::ZERO, 0, 0, 0, 1, 0).unwrap().unwrap(); + assert!((far.incident() - sample.incident() * 0.25).len() < 1e-14); + assert!(source.sample(Vec3::new(0.0, 0.0, 20.0), 0, 0, 0, 1, 0).unwrap().is_none()); + assert!(source.sample(Vec3::new(20.0, 0.0, 10.0), 0, 0, 0, 1, 0).unwrap().is_none()); + } + + #[test] + fn total_sampling_weight_does_not_grow_with_sample_count() { + let source = light(strip()); + // Undo each sample's geometric factor: sum incident*r²/cos must be Le*A, + // for EVERY N, rather than Le*A*N or Le*A/N. + for n in [1, 4, 16, 64] { + let mut sum = Vec3::ZERO; + for index in 0..n { + let sample = source.sample(Vec3::ZERO, 7, 0, index, n, 19).unwrap().unwrap(); + let cosine = (-source.normal()).dot(sample.direction()); + sum += sample.incident() * (sample.distance_mm().powi(2) / cosine); + } + assert!((sum - Vec3::new(8.0, 4.0, 2.0)).len() < 1e-12); + } + } + + fn scene() -> ProductScene { + let mesh = Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 0.0), Vec3::new(-20.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + let bounds = mesh.bounds(); + ProductScene { + bounds, + meshes: vec![ProductMesh { + transmission: None, + name: "original LED receiver".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap()), + faces: Vec::new(), + }], + } + } + fn request(options: RaytraceOptions) -> ImageRequest { + let mut camera = Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(options), + camera, + width: 1, + height: 1, + background: [0; 3], + transparent_background: false, + } + } + fn render(input: LedStripOptions, units: usize) -> Vec { + let mut options = RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }; + input.append_to(&mut options, 1).unwrap(); + let mut task = ImageTask::new(scene(), request(options.clone()), CancelToken::default(), options).unwrap(); + for _ in 0..10000 { + if let TaskPoll::Complete(png) = task.step(units).unwrap() { + return png; + } + } + panic!("bounded LED fixture did not finish"); + } + + #[test] + fn real_consumer_png_matches_analytic_lambert_pixel_and_partition() { + let png = render(LedStripOptions { color: [1.0; 3], ..strip() }, 1); + assert_eq!(png, render(LedStripOptions { color: [1.0; 3], ..strip() }, 128)); + let actual = ::image::load_from_memory(&png).unwrap().to_rgba8(); + // Center ray, area4, Le2, r10, Lambert1/pi; one shared tone-map. + let linear = 0.08 / std::f64::consts::PI; + let mapped = linear / (1.0 + linear); + let expected = ((1.055 * mapped.powf(1.0 / 2.4) - 0.055) * 255.0).round() as u8; + assert_eq!(actual.get_pixel(0, 0).0, [expected, expected, expected, 255]); + let dark = ::image::load_from_memory(&render(LedStripOptions { width_axis: [0.0, 1.0, 0.0], ..strip() }, 1)).unwrap().to_rgba8(); + assert_eq!(dark.get_pixel(0, 0).0, [0, 0, 0, 255]); + } + + #[test] + fn same_task_cancellation_refuses_partial_output() { + let mut options = RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }; + strip().append_to(&mut options, 64).unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request(options.clone()), cancel.clone(), options).unwrap(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } + + #[test] + fn admission_accounts_the_existing_rectangle_storage() { + let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let baseline = RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }; + let before = crate::raytrace::image::admit(&empty, &request(baseline.clone()), &baseline).unwrap(); + let mut options = baseline; + strip().append_to(&mut options, 64).unwrap(); + let after = crate::raytrace::image::admit(&empty, &request(options.clone()), &options).unwrap(); + assert!(after.estimated_total_bytes > before.estimated_total_bytes); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/mod.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/mod.rs new file mode 100644 index 000000000..fae2ced4e --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/mod.rs @@ -0,0 +1,1948 @@ +//! Product-image work and its device-independent, session-scoped protocol. +//! Hosts own execution; documents and history never contain these values. + +use std::fmt; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; + +use serde::{Deserialize, Serialize}; + +use crate::{BackendId, Camera, ExecutorId}; + +pub mod adaptive; +pub mod aging; +pub mod bloom; +mod cpu_budget; +pub(crate) mod encoding; +pub mod finishing; +mod host; +pub(crate) mod image; +pub mod interactive; +pub mod led_strip; +mod lens; +#[cfg(test)] +mod light_union_tests; +mod lighting; +pub mod linear_exr; +mod linear_exr_decode; +pub mod looks; +pub mod photographic; +mod png; +pub mod presentation; +mod punctual; +mod raster_lights; +mod regrade; +#[cfg(test)] +mod rt2_tests; +pub mod textures; +pub mod volume; + +pub use cpu_budget::{CpuBudget, CpuBudgetLimits, MAX_CPU_BODIES, MAX_CPU_SAMPLES_PER_PIXEL, MAX_CPU_TRIANGLES, MAX_CPU_WORK, NATIVE_CPU_POOL_BYTES}; +#[cfg(feature = "raytrace-cpu")] +pub(crate) use host::FRAME_METADATA_BYTES; +pub(crate) use host::Reservation; +pub use host::{ + CpuHost, HostKind, ImageHost, JobEnvironmentInfo, JobHandle, JobStatus, LinearAlphaConvention, LinearColourEncoding, LinearMasterInfo, + PartialPreviewInfo, PartialPreviewProjection, PreviewInfo, RenderFrame, RenderPartialPreview, RenderPreview, +}; +pub use image::{Admission, ImageTask, TaskPoll, admit, admit_geometry, admit_geometry_with_limits}; +pub use lens::ThinLens; +pub use lighting::{AreaLight, AreaLights, MAX_AREA_LIGHTS, StudioLighting, Sun, ToneMap}; +pub use png::PngTask; +pub use punctual::{PunctualDiagnostics, PunctualLightOptions, SpotConeOptions}; +pub use raster_lights::{ + deserialize as deserialize_raster_lights, deserialize_areas as deserialize_raster_area_lights, + deserialize_punctual as deserialize_raster_punctual_lights, validate as validate_raster_lights, validate_areas as validate_raster_area_lights, + validate_punctual as validate_raster_punctual_lights, +}; + +/// Native path-tracing ceilings, further restricted by the actual device. +/// Kept in the device-independent layer so saved intent and UI agree with execution. +pub const GPU_PATH_LIMITS: crate::RenderLimits = + crate::RenderLimits { max_dimension: 8192, max_pixels: 16_777_216, max_scratch_bytes: 8 * 1024 * 1024 * 1024 }; +pub const MAX_GPU_PATH_TRIANGLES: u64 = 8_000_000; +pub const MAX_GPU_PATH_BODIES: usize = 65_536; +pub const MAX_GPU_DIELECTRICS: usize = 32; + +/// Runtime sampling intent, separate from saved documents and device resources. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct JobOptions { + #[serde(skip_serializing_if = "aging::AgingStack::is_empty")] + pub aging: aging::AgingStack, + pub nested_media: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub volume: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub adaptive: Option, + /// Conditional Fresnel strata per primary sample; one keeps the old stream. + pub transmission_samples: u32, + + #[serde(default, skip_serializing_if = "finishing::Finishing::is_identity")] + pub finishing: finishing::Finishing, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backdrop: Option, + #[serde(default)] + pub linear_exr: bool, + pub samples: u32, + pub max_depth: u32, + pub seed: u32, + pub exposure_ev: f64, + pub lens: Option, + pub lighting: Option, + pub tone_map: ToneMap, + /// Optional final spatial filter. Raw progressive accumulation remains unchanged. + pub denoise: bool, +} + +impl Default for JobOptions { + fn default() -> Self { + Self { + aging: Default::default(), + nested_media: false, + volume: None, + adaptive: None, + transmission_samples: 1, + finishing: Default::default(), + backdrop: None, + linear_exr: false, + samples: 64, + max_depth: 8, + seed: 0, + exposure_ev: 0.0, + lens: None, + lighting: None, + tone_map: ToneMap::default(), + denoise: false, + } + } +} + +impl JobOptions { + pub fn validate(&self) -> Result<()> { + self.aging.validate()?; + if let Some(volume) = self.volume { + volume.validate()?; + if volume.active() && self.transmission_samples != 1 { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "volume transport requires one transmission stratum; glass combinations are not supported", + )); + } + if volume.active() && self.denoise { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "volume scattering has no surface-denoiser guides; disable denoising explicitly", + )); + } + } + if let Some(adaptive) = self.adaptive { + adaptive.validate(self.samples)?; + } + if !matches!(self.transmission_samples, 1 | 2 | 4) { + return Err(JobError::new(ErrorCode::InvalidRequest, "transmission_samples must be 1, 2 or 4")); + } + self.finishing.validate()?; + if let Some(backdrop) = self.backdrop { + backdrop.validate()?; + } + if let Some(lighting) = self.lighting { + lighting.validate()?; + } + if let Some(lens) = self.lens { + lens.validate()?; + } + if !(1..=4096).contains(&self.samples) + || !(1..=16).contains(&self.max_depth) + || !self.exposure_ev.is_finite() + || !(-32.0..=32.0).contains(&self.exposure_ev) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "samples must be 1..4096, depth 1..16 and exposure -32..32 EV")); + } + Ok(()) + } +} + +/// One bounded quantum of image work. Implementations check cancellation between quanta. +pub trait ImageWork: Send { + fn sampling_report(&self) -> Option { + None + } + /// Optional raw linear companion, moved exactly once after PNG completion. + /// The host validates intent, bounds, hashes and retains its memory lease. + fn take_linear_exr(&mut self) -> Option> { + None + } + fn step(&mut self, units: usize) -> Result; +} +impl ImageWork for ImageTask { + fn step(&mut self, units: usize) -> Result { + self.step(units) + } +} + +/// Device-independent executor boundary. The host owns admission leases and publication; +/// an executor owns computation only. GPU implementations live above the render crate. +pub trait ImageExecutor: Send + Sync { + fn supports_aging(&self) -> bool { + false + } + fn supports_photographic(&self) -> bool { + false + } + fn supports_subsurface(&self) -> bool { + false + } + fn supports_nested_media(&self) -> bool { + false + } + fn supports_volume(&self) -> bool { + false + } + fn supports_adaptive_sampling(&self) -> bool { + false + } + fn supports_transmission_sampling(&self) -> bool { + false + } + fn supports_bloom(&self) -> bool { + false + } + fn supports_finishing(&self) -> bool { + false + } + fn supports_linear_exr(&self) -> bool { + false + } + /// Host-owned logical allocation pool. This is a ceiling, not eager allocation. + /// Registration snapshots and validates it; unknown executors retain 512 MiB. + fn memory_limit_bytes(&self) -> u64 { + 512 * 1024 * 1024 + } + fn descriptor(&self) -> Result; + fn admit(&self, scene: &crate::ProductScene, request: &ImageRequest, options: JobOptions) -> Result; + fn begin(&self, scene: crate::ProductScene, request: ImageRequest, options: JobOptions, cancel: CancelToken) -> Result>; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct JobId { + pub session: u64, + pub serial: u64, + pub generation: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + Queued, + Preparing, + Running, + Encoding, + Cancelling, + Cancelled, + Completed, + Failed, +} + +impl Phase { + pub fn terminal(self) -> bool { + matches!(self, Self::Cancelled | Self::Completed | Self::Failed) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct Progress { + pub phase: Phase, + pub done: u64, + pub total: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + InvalidRequest, + LimitExceeded, + AllocationFailed, + HostUnavailable, + QueueFull, + TimedOut, + Cancelled, + InvalidScene, + EncodingFailed, + WrongOwner, + UnknownJob, + NotCompleted, + Internal, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct JobError { + pub code: ErrorCode, + pub message: String, +} + +impl JobError { + pub fn new(code: ErrorCode, message: impl Into) -> Self { + Self { code, message: message.into() } + } +} + +impl fmt::Display for JobError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}: {}", self.code, self.message) + } +} +impl std::error::Error for JobError {} + +pub type Result = std::result::Result; + +#[derive(Clone, Default)] +pub struct CancelToken(Arc); + +impl CancelToken { + pub fn cancel(&self) { + self.0.store(true, Ordering::Release); + } + pub fn is_cancelled(&self) -> bool { + self.0.load(Ordering::Acquire) + } + pub fn check(&self) -> Result<()> { + if self.is_cancelled() { Err(JobError::new(ErrorCode::Cancelled, "render cancelled")) } else { Ok(()) } + } +} + +/// Per-request execution choice, independent of viewport graphics presets. +/// Keep both variants parseable in builds without optional raytracing, so those +/// builds return an explicit capability error before capturing model geometry. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Integrator { + #[default] + Raster, + Raytrace, +} + +/// Explicit scene-reflection transport, separate from opaque roughness bounds. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReflectionMode { + Mirror, + RoughSpecular, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReflectionBody { + pub body: String, + pub mode: ReflectionMode, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ReflectionOptions { + #[serde(deserialize_with = "bounded_reflection_bodies")] + pub bodies: Vec, + pub max_bounces: u8, + pub samples: u8, +} +impl Default for ReflectionOptions { + fn default() -> Self { + Self { bodies: Vec::new(), max_bounces: 2, samples: 4 } + } +} +fn bounded_reflection_bodies<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + struct Bodies; + impl<'de> serde::de::Visitor<'de> for Bodies { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most64 reflection body overrides") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut values = Vec::new(); + while let Some(value) = seq.next_element()? { + if values.len() == 64 { + return Err(serde::de::Error::custom("at most64 reflection bodies")); + } + values.push(value); + } + Ok(values) + } + } + d.deserialize_seq(Bodies) +} +impl ReflectionOptions { + pub fn validate(&self) -> Result<()> { + if !(1..=8).contains(&self.max_bounces) || !(1..=64).contains(&self.samples) || self.bodies.len() > 64 || self.bodies.capacity() > 64 { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection bounds: 1..8 bounces, 1..64 samples, at most64 body slots")); + } + for (index, body) in self.bodies.iter().enumerate() { + if body.body.is_empty() + || body.body.len() > 128 + || body.body.capacity() > 128 + || self.bodies.iter().take(index).any(|other| other.body == body.body) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body names must be unique, nonempty and bounded to128 bytes")); + } + } + Ok(()) + } +} + +/// Linear-light runtime inputs. These are never design settings or GPU presets. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DirectionalLightOptions { + pub direction: [f64; 3], + pub color: [f64; 3], + pub intensity: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LightingPreset { + Neutral, + WarmCool, + KeyRim, +} + +impl LightingPreset { + /// Portable source values shared by CPU transport and light inspection. + pub fn directional_lights(self) -> Vec { + let light = |direction, color, intensity| DirectionalLightOptions { direction, color, intensity }; + match self { + Self::Neutral => crate::studio::LIGHTS.into_iter().map(|(d, intensity)| light([d.x, d.y, d.z], [1.0; 3], intensity)).collect(), + Self::WarmCool => vec![ + light([0.6, 0.0, 0.8], [1.0, 0.72, 0.48], 3.0), + light([-0.8, 0.0, 0.6], [0.45, 0.65, 1.0], 1.0), + light([0.0, -0.6, 0.8], [1.0; 3], 1.5), + ], + Self::KeyRim => vec![light([0.6, -0.4, 0.8], [1.0; 3], 3.0), light([-0.6, 0.4, 0.8], [0.6, 0.8, 1.0], 2.0)], + } + } +} + +/// Full world-space side vectors; U cross V is the emitting side. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RectangleLightOptions { + pub center_mm: [f64; 3], + pub edge_u_mm: [f64; 3], + pub edge_v_mm: [f64; 3], + pub color: [f64; 3], + pub intensity: f64, +} + +impl RectangleLightOptions { + /// Canonical numerical domain shared by CPU transport and schematic Raster. + pub(crate) fn validate(&self) -> Result<()> { + use solidcraft_geom::Vec3; + let vec = |v: [f64; 3]| Vec3::new(v[0], v[1], v[2]); + let c = vec(self.center_mm); + let u = vec(self.edge_u_mm); + let v = vec(self.edge_v_mm); + if !c.is_finite() + || !u.is_finite() + || !v.is_finite() + || !self.color.iter().all(|x| x.is_finite() && (0.0..=1.0).contains(x)) + || !self.intensity.is_finite() + || !(0.0..=64.0).contains(&self.intensity) + || !(1e-6..=1e6).contains(&u.len()) + || !(1e-6..=1e6).contains(&v.len()) + || (u.dot(v) / (u.len() * v.len())).abs() > 1e-10 + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid finite rectangular light")); + } + for a in [-0.5, 0.5] { + for b in [-0.5, 0.5] { + let p = c + u * a + v * b; + if !p.is_finite() || [p.x, p.y, p.z].into_iter().any(|x| x.abs() > 1e9) { + return Err(JobError::new(ErrorCode::InvalidRequest, "rectangular light corner exceeds world bounds")); + } + } + } + Ok(()) + } +} + +/// Explicit visual rotation about a certified planar face's outward normal. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AnisotropicOrientation { + #[default] + Zero, + QuarterTurn, +} + +/// Runtime-only captured planar face selector; no persistent naming is invented. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnisotropicFaceOptions { + pub body_index: usize, + #[serde(deserialize_with = "bounded_anisotropic_body_name")] + pub body_name: String, + pub face: u32, + pub tangent: [f64; 3], + pub orientation: AnisotropicOrientation, + pub roughness_x: f64, + pub roughness_y: f64, +} + +fn bounded_anisotropic_body_name<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + struct Name; + impl serde::de::Visitor<'_> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("captured body name of 1..1024 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 1024 { + return Err(E::custom("captured body name of 1..1024 bytes required")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + d.deserialize_str(Name) +} + +/// Emission is relative linear-sRGB radiance, independent of reflected color. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EmissionSides { + #[default] + Front, + Both, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SurfaceEmission { + pub body_index: usize, + #[serde(deserialize_with = "bounded_emission_body")] + pub body: String, + pub color: [f64; 3], + pub strength: f64, + #[serde(default)] + pub sides: EmissionSides, +} + +fn bounded_emission_body<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + struct Name; + impl<'de> serde::de::Visitor<'de> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a nonempty captured body name of at most 256 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 256 || value.chars().any(char::is_control) { + return Err(E::custom("invalid surface emission body name")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + d.deserialize_str(Name) +} + +impl SurfaceEmission { + pub fn validate(&self) -> Result<()> { + if self.body.is_empty() + || self.body.len() > 256 + || self.body.capacity() > 256 + || self.body.chars().any(char::is_control) + || !self.color.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) + || !self.strength.is_finite() + || !(0.0..=64.0).contains(&self.strength) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded surface emission")); + } + Ok(()) + } +} + +fn bounded_emissions<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct Emitters; + impl<'de> serde::de::Visitor<'de> for Emitters { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most 32 surface emitters") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut values = Vec::new(); + while let Some(value) = seq.next_element::()? { + if values.len() == 32 { + return Err(serde::de::Error::custom("at most 32 surface emitters")); + } + value.validate().map_err(serde::de::Error::custom)?; + values.try_reserve_exact(1).map_err(serde::de::Error::custom)?; + values.push(value); + } + Ok(values) + } + } + deserializer.deserialize_seq(Emitters).map(Some) +} + +/// Explicit runtime optics; never inferred from opacity or saved into a design. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DielectricBoundary { + ThinSheet, + ClosedBox, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DielectricOptions { + pub body_index: usize, + #[serde(deserialize_with = "bounded_dielectric_body_name")] + pub body_name: String, + pub boundary: DielectricBoundary, + pub ior: f64, + /// Per-channel Beer-Lambert extinction, inverse millimetres. + pub absorption_per_mm: [f64; 3], + /// Virtual normal thickness for ThinSheet only; ClosedBox requires zero. + pub thickness_mm: f64, +} + +/// Explicit constant secondary-ray environment; independent of display background. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RaytraceEnvironmentOptions { + pub color: [f64; 3], + pub intensity: f64, +} + +fn bounded_dielectric_body_name<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result { + struct Name; + impl serde::de::Visitor<'_> for Name { + type Value = String; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("captured body name of 1..1024 bytes") + } + fn visit_str(self, value: &str) -> std::result::Result { + if value.is_empty() || value.len() > 1024 { + return Err(E::custom("captured body name of 1..1024 bytes required")); + } + let mut name = String::new(); + name.try_reserve_exact(value.len()).map_err(E::custom)?; + name.push_str(value); + Ok(name) + } + } + deserializer.deserialize_str(Name) +} + +fn bounded_dielectrics<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result, D::Error> { + struct Inputs; + impl<'de> serde::de::Visitor<'de> for Inputs { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most eight dielectric overrides") + } + fn visit_seq>(self, mut sequence: A) -> std::result::Result { + let mut inputs = Vec::new(); + inputs.try_reserve_exact(8).map_err(serde::de::Error::custom)?; + while let Some(input) = sequence.next_element()? { + if inputs.len() == 8 { + return Err(serde::de::Error::custom("at most eight dielectric overrides")); + } + inputs.push(input); + } + Ok(inputs) + } + } + deserializer.deserialize_seq(Inputs) +} + +/// CPU camera sampling, independent of the registered GPU's `progressive` wire flag. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct CpuProgressiveOptions { + pub samples_per_pixel: u32, + pub seed: u32, +} + +impl Default for CpuProgressiveOptions { + fn default() -> Self { + Self { samples_per_pixel: 16, seed: 0 } + } +} + +impl CpuProgressiveOptions { + pub const MAX_PIXELS: u64 = 1_048_576; + pub const MAX_CAMERA_SAMPLES: u64 = 16_777_216; + + pub fn validate(&self) -> Result<()> { + if !(1..=64).contains(&self.samples_per_pixel) { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU progressive samples_per_pixel must be 1..64")); + } + Ok(()) + } + + /// Compatibility entry point: a caller that supplies no profile retains Compact. + pub fn validate_image(&self, width: u32, height: u32) -> Result<()> { + self.validate_image_with_budget(width, height, CpuBudget::Compact) + } + + pub fn validate_image_with_budget(&self, width: u32, height: u32, budget: CpuBudget) -> Result<()> { + budget.validate_image(width, height, Some(*self)) + } + + /// At most two reusable checkpoint reservations. A pinned consumer keeps its + /// slot charged; it does not authorize a new allocation per pass. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn checkpoint_slots(&self) -> u32 { + self.samples_per_pixel.saturating_sub(1).min(2) + } +} + +/// Runtime CPU dielectric transport policy, independent of resource and preview budgets. +/// StrictTir preserves deterministic TIR and refuses positive dielectric-depth tails. +/// It does not promise convergence or general physical glass support. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CpuDielectricTransport { + #[default] + LegacyBounded, + StrictTir, +} + +impl CpuDielectricTransport { + pub fn is_legacy(&self) -> bool { + *self == Self::LegacyBounded + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct RaytraceOptions { + #[serde(skip_serializing_if = "CpuDielectricTransport::is_legacy")] + pub dielectric_transport: CpuDielectricTransport, + #[serde(skip_serializing_if = "directional_shadow_disabled")] + pub directional_shadow_transmission: bool, + #[serde(skip_serializing_if = "CpuBudget::is_compact")] + pub budget: CpuBudget, + #[serde(skip_serializing_if = "Option::is_none")] + pub progressive: Option, + #[serde(deserialize_with = "bounded_dielectrics", skip_serializing_if = "Vec::is_empty")] + pub dielectrics: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, + #[serde(deserialize_with = "crate::surface_patterns::deserialize_effects", skip_serializing_if = "Option::is_none")] + pub surface_effects: Option>, + #[serde(deserialize_with = "bounded_emissions", skip_serializing_if = "Option::is_none")] + pub emissions: Option>, + /// Transient spatial pixel-box samples; independent of reflection attempts. + #[serde(skip_serializing_if = "single_primary_sample")] + pub primary_samples: u8, + pub reflections: Option, + pub anisotropic_faces: [Option; 2], + #[serde(deserialize_with = "punctual::bounded_punctual", skip_serializing_if = "Option::is_none")] + pub punctual_lights: Option>, + #[serde(deserialize_with = "bounded_area_lights", skip_serializing_if = "Option::is_none")] + pub area_lights: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub area_samples: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub seed: Option, + pub preset: Option, + #[serde(deserialize_with = "bounded_lights", skip_serializing_if = "Option::is_none")] + pub lights: Option>, + pub exposure_ev: f64, + pub shadows: bool, +} + +impl Default for RaytraceOptions { + fn default() -> Self { + Self { + dielectric_transport: CpuDielectricTransport::LegacyBounded, + directional_shadow_transmission: false, + budget: CpuBudget::Compact, + progressive: None, + punctual_lights: None, + area_lights: None, + area_samples: None, + seed: None, + primary_samples: 1, + emissions: None, + surface_effects: None, + dielectrics: Vec::new(), + environment: None, + anisotropic_faces: [None, None], + reflections: None, + preset: None, + lights: None, + exposure_ev: 0.0, + shadows: true, + } + } +} + +fn directional_shadow_disabled(value: &bool) -> bool { + !*value +} + +fn single_primary_sample(samples: &u8) -> bool { + *samples == 1 +} + +fn bounded_lights<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct Lights; + impl<'de> serde::de::Visitor<'de> for Lights { + type Value = Vec; + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("at most eight directional lights") + } + fn visit_seq>(self, mut sequence: A) -> std::result::Result { + let mut lights = Vec::new(); + while let Some(light) = sequence.next_element()? { + if lights.len() == 8 { + return Err(serde::de::Error::custom("at most eight directional lights")); + } + lights.push(light); + } + Ok(lights) + } + } + deserializer.deserialize_seq(Lights).map(Some) +} + +fn bounded_area_lights<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { + struct AreaLights; + impl<'de> serde::de::Visitor<'de> for AreaLights { + type Value = Vec; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("at most four rectangular lights") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut lights = Vec::new(); + while let Some(light) = seq.next_element()? { + if lights.len() == 4 { + return Err(serde::de::Error::custom("at most four rectangular lights")); + } + if lights.is_empty() { + lights.try_reserve_exact(4).map_err(serde::de::Error::custom)?; + if lights.capacity() > 4 { + return Err(serde::de::Error::custom("rectangular light capacity exceeds four")); + } + } + lights.push(light); + } + Ok(lights) + } + } + struct Optional; + impl<'de> serde::de::Visitor<'de> for Optional { + type Value = Option>; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("an optional bounded rectangular-light list") + } + fn visit_none(self) -> std::result::Result { + Ok(None) + } + fn visit_unit(self) -> std::result::Result { + Ok(None) + } + fn visit_some>(self, d: D) -> std::result::Result { + d.deserialize_seq(AreaLights).map(Some) + } + } + deserializer.deserialize_option(Optional) +} + +impl RaytraceOptions { + /// Dynamic dielectric capacities in one task or immutable request copy. + pub(crate) fn retained_dielectric_bytes(&self) -> Result { + let limit = || JobError::new(ErrorCode::LimitExceeded, "dielectric request capacity overflow"); + let mut bytes = (self.dielectrics.capacity() as u64).checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + for input in &self.dielectrics { + bytes = bytes.checked_add(input.body_name.capacity() as u64).ok_or_else(limit)?; + } + Ok(bytes) + } + /// Dynamic surface-effect capacities in one task or retained request copy. + pub(crate) fn retained_surface_effect_bytes(&self) -> Result { + let limit = || JobError::new(ErrorCode::LimitExceeded, "surface effect capacity overflow"); + let slots = self.surface_effects.as_ref().map_or(0, Vec::capacity) as u64; + let mut bytes = slots.checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + if let Some(values) = &self.surface_effects { + for value in values { + bytes = bytes.checked_add(value.body.capacity() as u64).ok_or_else(limit)?; + } + } + Ok(bytes) + } + /// Dynamic emission capacities in one options copy; included in both task and Record admission. + pub(crate) fn retained_emission_bytes(&self) -> Result { + let limit = || JobError::new(ErrorCode::LimitExceeded, "surface emission capacity overflow"); + let slots = self.emissions.as_ref().map_or(0, Vec::capacity) as u64; + let mut bytes = slots.checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + if let Some(values) = &self.emissions { + for value in values { + bytes = bytes.checked_add(value.body.capacity() as u64).ok_or_else(limit)?; + } + } + Ok(bytes) + } + /// One capacity calculation shared by host and engine preflight. + pub fn retained_bytes(&self) -> Result { + self.validate()?; + let limit = || JobError::new(ErrorCode::LimitExceeded, "raytrace request capacity overflow"); + let mut bytes = self + .lights + .as_ref() + .map_or(Some(0), |l| (l.capacity() as u64).checked_mul(std::mem::size_of::() as u64)) + .ok_or_else(limit)?; + for (capacity, size) in [ + (self.area_lights.as_ref().map_or(0, Vec::capacity), std::mem::size_of::()), + (self.punctual_lights.as_ref().map_or(0, Vec::capacity), std::mem::size_of::()), + ] { + bytes = bytes.checked_add((capacity as u64).checked_mul(size as u64).ok_or_else(limit)?).ok_or_else(limit)?; + } + if let Some(reflections) = &self.reflections { + let slots = (reflections.bodies.capacity() as u64).checked_mul(std::mem::size_of::() as u64).ok_or_else(limit)?; + bytes = bytes.checked_add(slots).ok_or_else(limit)?; + for body in &reflections.bodies { + bytes = bytes.checked_add(body.body.capacity() as u64).ok_or_else(limit)?; + } + } + for target in self.anisotropic_faces.iter().flatten() { + bytes = bytes.checked_add(target.body_name.capacity() as u64).ok_or_else(limit)?; + } + bytes = bytes.checked_add(self.retained_emission_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_surface_effect_bytes()?).ok_or_else(limit)?; + bytes = bytes.checked_add(self.retained_dielectric_bytes()?).ok_or_else(limit)?; + Ok(bytes) + } + /// No environment NEE on selected reflectors; rough transport must be purely metallic. + /// Rejecting every nonmetallic effective face prevents silently dropping its diffuse HDR. + pub fn validate_environment_reflections(&self, scene: &crate::ProductScene) -> Result<()> { + self.validate()?; + if self.environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either the HDR input or constant secondary environment")); + } + if let Some(reflections) = &self.reflections { + for selector in &reflections.bodies { + let mut bodies = scene.meshes.iter().filter(|b| b.name == selector.body); + let body = bodies.next().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "environment reflection body missing"))?; + if bodies.next().is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "ambiguous environment reflection body")); + } + if selector.mode == ReflectionMode::RoughSpecular + && (body.surface.is_none_or(|s| s.metallic() != 1.0) || body.faces.iter().any(|f| f.surface.is_none_or(|s| s.metallic() != 1.0))) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR rough reflection requires fully metallic body and face surfaces; diffuse/specular partition is not supported", + )); + } + } + } + for target in self.anisotropic_faces.iter().flatten() { + let mode = self.reflections.as_ref().and_then(|r| r.bodies.iter().find(|b| b.body == target.body_name).map(|b| b.mode)); + if mode != Some(ReflectionMode::RoughSpecular) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "HDR anisotropy requires a selected fully metallic rough reflector; anisotropic HDR direct lighting is not supported", + )); + } + } + Ok(()) + } + pub fn validate(&self) -> Result<()> { + // Opaque reflection has a separate bounded continuation policy. Do not + // advertise strict dielectric tails across that unqualified consumer. + if self.dielectric_transport == CpuDielectricTransport::StrictTir && self.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "strict CPU dielectric transport does not support selected opaque reflections yet")); + } + if let Some(progressive) = self.progressive { + self.budget.validate_samples(progressive.samples_per_pixel)?; + if self.primary_samples != 1 || self.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty() && r.samples != 1) { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "CPU progressive requires primary_samples: 1 and one reflection attempt per camera sample", + )); + } + // Smooth certified dielectric trees now complete one real camera + // sample before film accumulation. Anisotropic progressive transport + // remains unsupported; geometry/identity certificates run at capture. + if self.anisotropic_faces.iter().any(Option::is_some) { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU progressive does not support anisotropic inputs; use fixed sampling")); + } + } + if self.environment.is_some_and(|environment| { + !environment.color.into_iter().all(|v| v.is_finite() && (0.0..=1.0).contains(&v)) + || !environment.intensity.is_finite() + || !(0.0..=64.0).contains(&environment.intensity) + }) { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid constant raytrace environment")); + } + if self.dielectrics.len() > 8 || self.dielectrics.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight dielectric overrides")); + } + for (index, input) in self.dielectrics.iter().enumerate() { + if input.body_name.is_empty() + || input.body_name.len() > 1024 + || input.body_name.capacity() > 1024 + || !input.ior.is_finite() + || !(1.0..=3.0).contains(&input.ior) + || !input.absorption_per_mm.into_iter().all(|v| v.is_finite() && (0.0..=100.0).contains(&v)) + || !input.thickness_mm.is_finite() + || !(0.0..=10000.0).contains(&input.thickness_mm) + || (input.boundary == DielectricBoundary::ClosedBox && input.thickness_mm != 0.0) + || self.dielectrics.iter().take(index).any(|previous| previous.body_index == input.body_index) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid or duplicate dielectric override")); + } + } + if let Some(values) = &self.surface_effects { + if values.capacity() > 32 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most 32 surface-effect reserved slots")); + } + crate::surface_patterns::validate_effects(values)?; + } + if let Some(values) = &self.emissions { + if values.len() > 32 || values.capacity() > 32 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most 32 surface emitters")); + } + for (i, value) in values.iter().enumerate() { + value.validate()?; + if values.iter().take(i).any(|other| other.body_index == value.body_index) { + return Err(JobError::new(ErrorCode::InvalidRequest, "duplicate surface emission target")); + } + } + } + let area_count = self.area_lights.as_ref().map_or(0, Vec::len); + if self.area_lights.as_ref().is_some_and(|v| v.len() > 4 || v.capacity() > 4) { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most four rectangular lights and reserved slots")); + } + if area_count == 0 && (self.area_samples.is_some() || self.seed.is_some()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "area_samples and seed require nonempty area_lights")); + } + if self.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) { + return Err(JobError::new(ErrorCode::InvalidRequest, "area_samples must be 1, 4, 16 or 64")); + } + let directional_count = self.lights.as_ref().map_or_else(|| if self.preset == Some(LightingPreset::KeyRim) { 2 } else { 3 }, Vec::len); + if directional_count + .checked_add(area_count) + .and_then(|n| n.checked_add(self.punctual_lights.as_ref().map_or(0, Vec::len))) + .is_none_or(|n| n > 20) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most twenty combined directional, punctual and rectangular lights")); + } + if let Some(lights) = &self.area_lights { + for light in lights { + light.validate()?; + } + } + if let Some(lights) = &self.punctual_lights { + if lights.len() > 8 || lights.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight point/spot sources and reserved slots")); + } + for light in lights { + light.validate()?; + } + } + if !matches!(self.primary_samples, 1 | 4 | 16) { + return Err(JobError::new(ErrorCode::InvalidRequest, "primary samples must be exactly 1, 4 or 16")); + } + + if let Some(reflections) = &self.reflections { + reflections.validate()?; + } + for (i, target) in self.anisotropic_faces.iter().enumerate().filter_map(|(i, target)| target.as_ref().map(|target| (i, target))) { + if target.body_name.is_empty() + || target.body_name.len() > 1024 + || target.body_name.capacity() > 1024 + || !target.tangent.iter().all(|v| v.is_finite()) + || !target.tangent.iter().any(|v| *v != 0.0) + || ![target.roughness_x, target.roughness_y].into_iter().all(|v| v.is_finite() && (crate::surface::MIN_ROUGHNESS..=1.0).contains(&v)) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded anisotropic planar face options")); + } + if self.anisotropic_faces.iter().skip(i + 1).flatten().any(|other| target.body_index == other.body_index && target.face == other.face) { + return Err(JobError::new(ErrorCode::InvalidRequest, "duplicate anisotropic captured face")); + } + } + if self.reflections.as_ref().is_some_and(|r| { + r.bodies.iter().any(|b| b.mode == ReflectionMode::Mirror && self.anisotropic_faces.iter().flatten().any(|t| t.body_name == b.body)) + }) { + return Err(JobError::new(ErrorCode::InvalidRequest, "delta mirror cannot have anisotropic rough axes")); + } + if self.preset.is_some() && self.lights.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "choose either a lighting preset or custom lights")); + } + if !self.exposure_ev.is_finite() || !(-32.0..=32.0).contains(&self.exposure_ev) { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace exposure_ev must be finite and within -32..32")); + } + if let Some(lights) = &self.lights { + if lights.len() > 8 || lights.capacity() > 8 { + return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight directional lights")); + } + for light in lights { + let direction_valid = light.direction.iter().all(|n| n.is_finite() && n.abs() <= 1e9) && light.direction.iter().any(|n| *n != 0.0); + if !direction_valid + || !light.color.iter().all(|n| n.is_finite() && (0.0..=1.0).contains(n)) + || !light.intensity.is_finite() + || !(0.0..=64.0).contains(&light.intensity) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid bounded directional light")); + } + } + } + if self.directional_shadow_transmission + && (!self.shadows + || self.dielectrics.is_empty() + || self.reflections.is_some() + || self.anisotropic_faces.iter().any(Option::is_some) + || self.environment.is_some() + || self.punctual_lights.as_ref().is_some_and(|lights| !lights.is_empty()) + || self.area_lights.as_ref().is_some_and(|lights| !lights.is_empty())) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "directional shadow transmission requires shadows and selected dielectrics without reflections, anisotropy, environment or local lights", + )); + } + Ok(()) + } +} + +/// Fully resolved input; no mutable session, topology graph or GPU resources. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImageRequest { + /// Captured CPU publication policy, separate from saved sampling intent. + /// False survives request serialization; omission preserves every-pass mode. + #[serde(default = "default_cpu_progressive_every_pass", skip_serializing_if = "cpu_progressive_every_pass_enabled")] + pub cpu_progressive_every_pass: bool, + /// Resolved Raster-only capture of RenderSetup.exposure_ev, never a second authority. + #[serde(default, skip_serializing_if = "zero_raster_exposure")] + pub raster_exposure_ev: f64, + /// Explicit transient opaque Raster rig; None keeps the original implicit studio. + #[serde(default, deserialize_with = "deserialize_raster_lights", skip_serializing_if = "Option::is_none")] + pub raster_lights: Option>, + /// Runtime-only local rig. Any explicit local collection suppresses implicit studio lights. + #[serde(default, deserialize_with = "deserialize_raster_punctual_lights", skip_serializing_if = "Option::is_none")] + pub raster_punctual_lights: Option>, + #[serde(default, deserialize_with = "deserialize_raster_area_lights", skip_serializing_if = "Option::is_none")] + pub raster_area_lights: Option>, + /// Transient visibility of the three implicit studio lights; never saved in a design. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub studio_weights: Option<[f64; 3]>, + /// Captured GPU resources stay in admitted work, never in status or saved data. + #[serde(skip)] + pub environment: Option>, + #[serde(skip)] + pub textures: Option>, + #[serde(default)] + pub integrator: Integrator, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub raytrace: Option, + pub camera: Camera, + pub width: u32, + pub height: u32, + pub background: [u8; 3], + pub transparent_background: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ColourEncoding { + Srgb, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum AlphaConvention { + Straight, +} + +fn default_cpu_progressive_every_pass() -> bool { + true +} + +fn cpu_progressive_every_pass_enabled(value: &bool) -> bool { + *value +} + +impl ImageRequest { + pub fn has_local_raster_lights(&self) -> bool { + self.raster_punctual_lights.is_some() || self.raster_area_lights.is_some() + } + + pub fn has_explicit_raster_lights(&self) -> bool { + self.raster_lights.is_some() || self.has_local_raster_lights() + } + + /// Only the new local-rig route charges each bounded light evaluation. + /// Existing directional and implicit routes retain their original pixel budget. + pub(super) fn raster_light_work_factor(&self) -> Result { + if !self.has_local_raster_lights() { + return Ok(1); + } + self.validate_raster_request()?; + let count = self + .raster_lights + .as_ref() + .map_or(0, Vec::len) + .checked_add(self.raster_punctual_lights.as_ref().map_or(0, Vec::len)) + .and_then(|n| n.checked_add(self.raster_area_lights.as_ref().map_or(0, Vec::len))) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster light work overflow"))?; + u64::try_from(count.max(1)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "Raster light work overflow")) + } + + /// Reject explicit Raster intent before allocating or entering another producer. + pub fn validate_raster_request(&self) -> Result<()> { + if !self.raster_exposure_ev.is_finite() || !(-32.0..=32.0).contains(&self.raster_exposure_ev) { + return Err(JobError::new(ErrorCode::InvalidRequest, "Raster exposure must be finite and within -32..32 EV")); + } + if self.raster_exposure_ev != 0.0 + && (self.integrator != Integrator::Raster || self.raytrace.is_some() || self.environment.is_some() || self.textures.is_some()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "Raster exposure cannot enter another integrator or captured GPU resources")); + } + raster_lights::validate(&self.raster_lights)?; + raster_lights::validate_punctual(&self.raster_punctual_lights)?; + raster_lights::validate_areas(&self.raster_area_lights)?; + if self.has_explicit_raster_lights() + && (self.integrator != Integrator::Raster + || self.raytrace.is_some() + || self.studio_weights.is_some() + || self.environment.is_some() + || self.textures.is_some()) + { + return Err(JobError::new( + ErrorCode::InvalidRequest, + "explicit Raster lights require Raster without raytrace, GPU resources or studio_weights", + )); + } + Ok(()) + } + + pub fn raster_lights_retained_bytes(&self) -> Result { + raster_lights::retained_bytes(&self.raster_lights)? + .checked_add(raster_lights::local_retained_bytes(&self.raster_punctual_lights, &self.raster_area_lights)?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster light retained size overflow")) + } + + pub(super) fn raster_lights_task_bytes(&self) -> Result { + raster_lights::task_bytes(&self.raster_lights)? + .checked_add(raster_lights::local_task_bytes(&self.raster_punctual_lights, &self.raster_area_lights)?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster task light size overflow")) + } + + /// Internal status/task copy: the new Vec allocation is bounded and fallible. + pub(super) fn try_clone_for_host(&self) -> Result { + self.validate_raster_request()?; + // Preserve the old path, including existing unrelated payload semantics. + if !self.has_explicit_raster_lights() { + return Ok(self.clone()); + } + Ok(Self { + cpu_progressive_every_pass: self.cpu_progressive_every_pass, + raster_exposure_ev: self.raster_exposure_ev, + raster_lights: raster_lights::try_copy(&self.raster_lights)?, + raster_punctual_lights: raster_lights::try_copy_punctual(&self.raster_punctual_lights)?, + raster_area_lights: raster_lights::try_copy_areas(&self.raster_area_lights)?, + studio_weights: self.studio_weights, + environment: self.environment.clone(), + textures: self.textures.clone(), + integrator: self.integrator, + raytrace: None, // validated absent above, never clone-then-clear + camera: self.camera, + width: self.width, + height: self.height, + background: self.background, + transparent_background: self.transparent_background, + }) + } + pub fn cpu_budget(&self) -> CpuBudget { + if self.integrator == Integrator::Raytrace { + self.raytrace.as_ref().map_or(CpuBudget::Compact, |options| options.budget) + } else { + CpuBudget::Compact + } + } + + /// Small GPU resource summaries survive work completion and keep their own host lease. + pub fn retained_resource_metadata_bytes(&self) -> u64 { + let environment = self + .environment + .as_ref() + .map_or(0, |source| (std::mem::size_of::() + source.info().source_sha256.len()) as u64); + environment + if self.textures.is_some() { std::mem::size_of::() as u64 } else { 0 } + } +} + +fn zero_raster_exposure(value: &f64) -> bool { + *value == 0.0 +} + +#[derive(Clone, Debug, Serialize)] +pub struct FrameInfo { + pub job: JobId, + pub scene_generation: u64, + pub backend: BackendId, + pub executor: ExecutorId, + pub width: u32, + pub height: u32, + pub encoding: ColourEncoding, + pub alpha: AlphaConvention, + /// Exact encoded PNG length, not pixel storage or reserved Vec capacity. + pub png_bytes: u64, + /// Cached lowercase SHA-256 of those encoded bytes, computed before completion. + pub png_sha256: String, +} +#[cfg(test)] +mod runtime_request_roundtrip_tests { + + fn raster_local_test_request() -> ImageRequest { + serde_json::from_value( + serde_json::json!({"camera":crate::Camera::default(),"width":8,"height":8,"background":[0,0,0],"transparent_background":false}), + ) + .unwrap() + } + + fn raster_local_test_point() -> PunctualLightOptions { + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 2.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + } + } + + fn raster_local_test_rectangle() -> RectangleLightOptions { + RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 2.0, + } + } + + #[test] + fn raster_local_wire_omission_null_empty_and_host_copy_keep_distinct_intent() { + let legacy = raster_local_test_request(); + let wire = serde_json::to_value(&legacy).unwrap(); + assert!(wire.get("raster_punctual_lights").is_none()); + assert!(wire.get("raster_area_lights").is_none()); + assert!(!legacy.has_explicit_raster_lights()); + let mut null = wire.clone(); + null["raster_punctual_lights"] = serde_json::Value::Null; + null["raster_area_lights"] = serde_json::Value::Null; + let decoded: ImageRequest = serde_json::from_value(null).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), wire); + for key in ["raster_punctual_lights", "raster_area_lights"] { + let mut explicit = wire.clone(); + explicit[key] = serde_json::json!([]); + let input: ImageRequest = serde_json::from_value(explicit).unwrap(); + assert!(input.has_explicit_raster_lights() && input.has_local_raster_lights()); + assert!(input.raster_lights.is_none(), "no implicit directional materialisation"); + assert_eq!(input.raster_light_work_factor().unwrap(), 1); + let copy = input.try_clone_for_host().unwrap(); + assert_eq!(serde_json::to_value(copy).unwrap(), serde_json::to_value(input).unwrap()); + } + } + + #[test] + fn raster_local_eight_shared_point_spot_four_areas_and_directional_caps_are_independent() { + let mut input = raster_local_test_request(); + let point = raster_local_test_point(); + let mut spot = point; + spot.cone = Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); + input.raster_lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]); + assert_eq!(input.raster_light_work_factor().unwrap(), 1, "old directional work path unchanged"); + input.raster_punctual_lights = Some(vec![point, spot, point, spot, point, spot, point, spot]); + input.raster_area_lights = Some(vec![raster_local_test_rectangle(); 4]); + input.validate_raster_request().unwrap(); + assert_eq!(input.raster_light_work_factor().unwrap(), 20); + input.raster_punctual_lights.as_mut().unwrap().push(point); + assert_eq!(input.validate_raster_request().unwrap_err().code, ErrorCode::InvalidRequest); + assert!(serde_json::from_value::(serde_json::to_value(&input).unwrap()).is_err()); + input.raster_punctual_lights = Some(vec![point]); + input.raster_area_lights.as_mut().unwrap().push(raster_local_test_rectangle()); + assert!(input.validate_raster_request().is_err()); + assert!(serde_json::from_value::(serde_json::to_value(input).unwrap()).is_err()); + } + + #[test] + fn raster_local_spare_capacities_refuse_before_copy_or_task_reservation() { + let mut input = raster_local_test_request(); + input.raster_punctual_lights = Some(Vec::with_capacity(9)); + assert!(input.try_clone_for_host().is_err()); + assert!(input.raster_lights_retained_bytes().is_err()); + assert!(input.raster_lights_task_bytes().is_err()); + input.raster_punctual_lights = None; + input.raster_area_lights = Some(Vec::with_capacity(5)); + assert!(input.try_clone_for_host().is_err()); + assert!(input.raster_lights_retained_bytes().is_err()); + assert!(input.raster_lights_task_bytes().is_err()); + } + + #[test] + fn raster_local_fallible_fixed_dto_copy_preserves_values_and_accounts_both_families() { + let mut input = raster_local_test_request(); + input.raster_punctual_lights = Some(vec![raster_local_test_point()]); + input.raster_area_lights = Some(vec![raster_local_test_rectangle()]); + let expected = (input.raster_punctual_lights.as_ref().unwrap().capacity() * std::mem::size_of::() + + input.raster_area_lights.as_ref().unwrap().capacity() * std::mem::size_of::()) as u64; + assert_eq!(input.raster_lights_retained_bytes().unwrap(), expected); + let task_fee = (8 * std::mem::size_of::() + 4 * std::mem::size_of::()) as u64; + assert_eq!(input.raster_lights_task_bytes().unwrap(), task_fee); + let copy = input.try_clone_for_host().unwrap(); + assert_eq!(copy.raster_punctual_lights, input.raster_punctual_lights); + assert_eq!(copy.raster_area_lights, input.raster_area_lights); + assert!(copy.raster_lights_retained_bytes().unwrap() <= task_fee); + input.raster_punctual_lights.as_mut().unwrap()[0].intensity = 0.0; + input.raster_area_lights.as_mut().unwrap()[0].intensity = 0.0; + assert_eq!(copy.raster_punctual_lights.as_ref().unwrap()[0].intensity, 2.0); + assert_eq!(copy.raster_area_lights.as_ref().unwrap()[0].intensity, 2.0); + } + + #[test] + fn raster_local_empty_intent_still_refuses_other_producers_and_implicit_weights() { + for family in [0, 1] { + let mut input = raster_local_test_request(); + if family == 0 { + input.raster_punctual_lights = Some(Vec::new()); + } else { + input.raster_area_lights = Some(Vec::new()); + } + input.studio_weights = Some([0.0; 3]); + assert!(input.validate_raster_request().is_err()); + input.studio_weights = None; + input.raytrace = Some(Default::default()); + assert!(input.validate_raster_request().is_err()); + input.raytrace = None; + input.integrator = Integrator::Raytrace; + assert!(input.validate_raster_request().is_err()); + assert!(super::interactive::cpu_request(&input).is_err()); + } + } + + #[test] + fn raster_local_shared_rectangle_validator_preserves_canonical_bounds_and_error_order() { + let mut rectangle = raster_local_test_rectangle(); + rectangle.color = [0.0; 3]; + rectangle.intensity = 0.0; + rectangle.edge_u_mm = [1.0, 1.0, 0.0]; + assert_eq!(rectangle.validate().unwrap_err().message, "invalid finite rectangular light"); + rectangle = raster_local_test_rectangle(); + rectangle.center_mm = [1e9, 0.0, 0.0]; + assert_eq!(rectangle.validate().unwrap_err().message, "rectangular light corner exceeds world bounds"); + let mut input = raster_local_test_request(); + input.raster_area_lights = Some(vec![rectangle.clone()]); + assert!(input.validate_raster_request().is_err()); + let options = RaytraceOptions { area_lights: Some(vec![rectangle]), ..Default::default() }; + assert_eq!(options.validate().unwrap_err().message, "rectangular light corner exceeds world bounds"); + } + + #[test] + fn raster_light_wire_is_nullable_bounded_strict_and_fallibly_copied() { + #[derive(Serialize, Deserialize)] + #[serde(deny_unknown_fields)] + struct Rig { + #[serde(default, deserialize_with = "super::raster_lights::deserialize", skip_serializing_if = "Option::is_none")] + raster_lights: Option>, + } + use serde_json::json; + for value in [json!({}), json!({"raster_lights":null})] { + let rig: Rig = serde_json::from_value(value).unwrap(); + assert!(rig.raster_lights.is_none()); + assert_eq!(serde_json::to_value(rig).unwrap(), json!({})); + } + let light = json!({"direction":[0.0,0.0,1.0],"color":[0.25,0.5,1.0],"intensity":2.0}); + for count in [0, 1, 8] { + let rig: Rig = serde_json::from_value(json!({"raster_lights":vec![light.clone();count]})).unwrap(); + assert_eq!(rig.raster_lights.as_ref().unwrap().len(), count); + assert!(rig.raster_lights.as_ref().unwrap().capacity() <= 8); + let copy = super::raster_lights::try_copy(&rig.raster_lights).unwrap(); + assert_eq!(copy, rig.raster_lights); + assert!(copy.as_ref().unwrap().capacity() <= 8); + assert_eq!(serde_json::to_value(rig).unwrap(), json!({"raster_lights":vec![light.clone();count]})); + } + assert!(serde_json::from_value::(json!({"raster_lights":vec![light.clone();9]})).is_err()); + for value in [ + json!(true), + json!({}), + json!([{"direction":[0,0,0],"color":[1,1,1],"intensity":0}]), + json!([{"direction":[0,0,1],"color":[1,1,1],"intensity":1,"shadows":true}]), + ] { + assert!(serde_json::from_value::(json!({"raster_lights":value})).is_err()); + } + let mut excessive = Vec::with_capacity(9); + excessive.push(DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + assert!(super::raster_lights::try_copy(&Some(excessive)).is_err()); + for intensity in [f64::NAN, f64::INFINITY, -1.0, 65.0] { + let invalid = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity }]); + assert!(super::raster_lights::try_copy(&invalid).is_err()); + } + } + + use super::*; + + #[test] + fn dielectric_transport_wire_policy_preserves_legacy_and_rejects_hostile_values() { + let legacy: RaytraceOptions = serde_json::from_value(serde_json::json!({})).unwrap(); + assert_eq!(legacy.dielectric_transport, CpuDielectricTransport::LegacyBounded); + assert!(serde_json::to_value(&legacy).unwrap().get("dielectric_transport").is_none()); + let strict: RaytraceOptions = serde_json::from_value(serde_json::json!({"dielectric_transport":"strict_tir"})).unwrap(); + strict.validate().unwrap(); + assert_eq!(serde_json::to_value(&strict).unwrap()["dielectric_transport"], "strict_tir"); + for value in [serde_json::json!(null), serde_json::json!(true), serde_json::json!(7), serde_json::json!("unlimited"), serde_json::json!({})] { + assert!(serde_json::from_value::(serde_json::json!({"dielectric_transport":value})).is_err()); + } + } + + #[test] + fn strict_dielectric_policy_refuses_unqualified_opaque_continuations_without_mutation() { + let options = RaytraceOptions { + dielectric_transport: CpuDielectricTransport::StrictTir, + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: "Body".into(), mode: ReflectionMode::Mirror }], + ..Default::default() + }), + ..Default::default() + }; + let before = options.clone(); + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + assert_eq!(options, before); + RaytraceOptions { dielectric_transport: CpuDielectricTransport::LegacyBounded, ..options }.validate().unwrap(); + } + #[test] + fn default_preset_and_empty_lights_requests_roundtrip_without_invalid_null_sequence() { + for options in [ + RaytraceOptions::default(), + RaytraceOptions { preset: Some(LightingPreset::Neutral), ..Default::default() }, + RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }, + ] { + let value = serde_json::to_value(&options).unwrap(); + if options.lights.is_none() { + assert!(value.get("lights").is_none()); + } else { + assert_eq!(value.get("lights").unwrap(), &serde_json::json!([])); + } + let decoded: RaytraceOptions = serde_json::from_value(value).unwrap(); + assert_eq!(decoded, options); + assert!(decoded.validate().is_ok()); + } + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap(), RaytraceOptions::default()); + } + + #[test] + fn cpu_progressive_options_are_optional_strict_and_bounded_before_capture() { + use serde_json::json; + assert!(serde_json::to_value(RaytraceOptions::default()).unwrap().get("progressive").is_none()); + assert_eq!(serde_json::from_value::(json!({"progressive":null})).unwrap(), RaytraceOptions::default()); + let options: RaytraceOptions = serde_json::from_value(json!({"progressive":{"samples_per_pixel":3,"seed":u32::MAX}})).unwrap(); + options.validate().unwrap(); + assert_eq!(serde_json::from_value::(serde_json::to_value(&options).unwrap()).unwrap(), options); + for invalid in [json!({"seed":-1}), json!({"seed":4294967296_u64}), json!({"seed":0.5}), json!({"adaptive":true})] { + assert!(serde_json::from_value::(invalid).is_err()); + } + for samples_per_pixel in [0, 65, u32::MAX] { + assert!(CpuProgressiveOptions { samples_per_pixel, seed: 0 }.validate().is_err()); + } + for samples_per_pixel in [1, 2, 3, 16, 64] { + CpuProgressiveOptions { samples_per_pixel, seed: 0 }.validate_image(512, 512).unwrap(); + } + CpuProgressiveOptions::default().validate_image(1024, 1024).unwrap(); + assert!(CpuProgressiveOptions { samples_per_pixel: 17, seed: 0 }.validate_image(1024, 1024).is_err()); + for (width, height) in [(0, 1), (1, 0), (1025, 1024), (4097, 1), (u32::MAX, u32::MAX)] { + assert!(CpuProgressiveOptions { samples_per_pixel: 1, seed: 0 }.validate_image(width, height).is_err()); + } + } + + #[test] + fn progressive_rejects_incompatible_sampling_without_changing_fixed_aa() { + let progressive = Some(CpuProgressiveOptions::default()); + for primary_samples in [4, 16] { + let fixed = RaytraceOptions { primary_samples, ..Default::default() }; + fixed.validate().unwrap(); + assert!(RaytraceOptions { progressive, ..fixed }.validate().is_err()); + } + let reflections = ReflectionOptions { + bodies: vec![ReflectionBody { body: "Body".into(), mode: ReflectionMode::RoughSpecular }], + samples: 4, + max_bounces: 2, + }; + assert!(RaytraceOptions { progressive, reflections: Some(reflections), ..Default::default() }.validate().is_err()); + let area = RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [1.0, 0.0, 0.0], + edge_v_mm: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }; + RaytraceOptions { progressive, area_lights: Some(vec![area]), ..Default::default() }.validate().unwrap(); + let dielectric = DielectricOptions { + body_index: 0, + body_name: "Body".into(), + boundary: DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }; + // Superseded global rejection: smooth optical trees are implemented per + // camera sample; capture-time certification remains separately required. + RaytraceOptions { progressive, dielectrics: vec![dielectric], ..Default::default() }.validate().unwrap(); + let face = AnisotropicFaceOptions { + body_index: 0, + body_name: "Body".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: AnisotropicOrientation::Zero, + roughness_x: 0.2, + roughness_y: 0.6, + }; + assert!(RaytraceOptions { progressive, anisotropic_faces: [Some(face), None], ..Default::default() }.validate().is_err()); + RaytraceOptions { progressive, area_lights: Some(Vec::new()), ..Default::default() }.validate().unwrap(); + } + + #[test] + fn progressive_rectangle_and_led_admission_preserves_source_limits_and_atomic_rejection() { + let strip = led_strip::LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 2.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }; + for samples in [1, 4, 16, 64] { + let mut options = RaytraceOptions { + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 97 }), + lights: Some(Vec::new()), + ..Default::default() + }; + for count in 1..=4 { + strip.append_to(&mut options, samples).unwrap(); + options.validate().unwrap(); + assert_eq!(options.area_lights.as_ref().unwrap().len(), count); + assert_eq!( + options.retained_bytes().unwrap(), + (options.area_lights.as_ref().unwrap().capacity() * std::mem::size_of::()) as u64 + ); + } + let before = options.clone(); + let capacity = options.area_lights.as_ref().unwrap().capacity(); + assert!(strip.append_to(&mut options, samples).is_err()); + assert_eq!(options, before); + assert_eq!(options.area_lights.as_ref().unwrap().capacity(), capacity); + options.area_lights.as_mut().unwrap().pop(); + let before = options.clone(); + let conflicting = if samples == 1 { 4 } else { 1 }; + assert!(strip.append_to(&mut options, conflicting).is_err()); + assert_eq!(options, before); + for invalid in [0, 2, 65, u32::MAX] { + let mut hostile = options.clone(); + hostile.area_samples = Some(invalid); + assert!(hostile.validate().is_err()); + } + let mut hostile = options.clone(); + hostile.area_lights.as_mut().unwrap()[0].intensity = f64::NAN; + assert!(hostile.validate().is_err()); + } + let mut maximum = RaytraceOptions { + progressive: Some(CpuProgressiveOptions::default()), + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]), + punctual_lights: Some(vec![ + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }; + 8 + ]), + ..Default::default() + }; + for _ in 0..4 { + strip.append_to(&mut maximum, 16).unwrap(); + } + maximum.validate().unwrap(); + maximum.area_lights.as_mut().unwrap().push(strip.rectangle().unwrap()); + assert!(maximum.validate().is_err()); + for options in [ + RaytraceOptions { progressive: Some(CpuProgressiveOptions::default()), area_samples: Some(16), ..Default::default() }, + RaytraceOptions { progressive: Some(CpuProgressiveOptions::default()), seed: Some(7), ..Default::default() }, + ] { + assert!(options.validate().is_err()); + } + } +} + +/// Fixed representative presentation plan; fitting never grants source admission. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PartialPreviewPlan { + source_width: u32, + source_height: u32, + width: u32, + height: u32, +} +impl PartialPreviewPlan { + pub fn source_width(&self) -> u32 { + self.source_width + } + pub fn source_height(&self) -> u32 { + self.source_height + } + pub fn width(&self) -> u32 { + self.width + } + pub fn height(&self) -> u32 { + self.height + } + pub fn new(source_width: u32, source_height: u32) -> Result { + if source_width == 0 || source_height == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview source dimensions must be positive")); + } + let edge = source_width.max(source_height); + let fit = |side: u32| { + if edge <= 1024 { side } else { ((u64::from(side) * 1024 + u64::from(edge) / 2) / u64::from(edge)).max(1) as u32 } + }; + Ok(Self { source_width, source_height, width: fit(source_width), height: fit(source_height) }) + } + pub fn validate(&self) -> Result<()> { + if *self != Self::new(self.source_width, self.source_height)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview dimensions differ from the fixed plan")); + } + Ok(()) + } + pub fn pixels(&self) -> u64 { + u64::from(self.width) * u64::from(self.height) + } + pub fn source_index(&self, preview_index: usize) -> Result { + self.validate()?; + let index = u64::try_from(preview_index).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial preview index overflow"))?; + if index >= self.pixels() { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview index outside its plan")); + } + let x = (index % u64::from(self.width)) * u64::from(self.source_width) / u64::from(self.width); + let y = (index / u64::from(self.width)) * u64::from(self.source_height) / u64::from(self.height); + let source = y + .checked_mul(u64::from(self.source_width)) + .and_then(|v| v.checked_add(x)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial source index overflow"))?; + usize::try_from(source).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial source index exceeds address space")) + } + pub fn encoded_limit(&self) -> Result { + self.validate()?; + self.pixels() + .checked_mul(8) + .and_then(|v| v.checked_add(65_536)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial PNG capacity overflow")) + } + pub fn covered_bytes(&self) -> Result { + self.validate()?; + self.pixels().checked_mul(4).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial coverage capacity overflow")) + } + pub fn snapshot_work(&self) -> Result { + self.validate()?; + self.pixels() + .checked_mul(14) + .and_then(|v| v.checked_add(65_538)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial work bound overflow")) + } + /// Two retained payload slots; existing admitted RGBA/encoder scratch is reused. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn additional_bytes(&self) -> Result { + self.slot_bytes()? + .checked_mul(2) + .and_then(|v| v.checked_add(1024)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial preview admission overflow")) + } + pub(crate) fn slot_bytes(&self) -> Result { + self.encoded_limit()? + .checked_add(self.covered_bytes()?) + .and_then(|v| v.checked_add(2048)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retained slot overflow")) + } +} + +/// Explicit protected-feedback aggregate ceiling; the ordinary MAX_CPU_WORK is unchanged. +// At most 1024² representatives: 14 work units each plus 65,538 codec/hash +// overhead. At most 64 early milestones and MAX_SPP-1 complete-pass snapshots. +// This Cartesian upper bound is deliberately conservative; ordinary work is unchanged. +pub const MAX_PROTECTED_CPU_WORK: u64 = MAX_CPU_WORK + 14_745_602 * (MAX_CPU_SAMPLES_PER_PIXEL as u64 + 63); + +/// Checked per-job feedback policy, not an admission token or an arbitrary work envelope. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProtectedPreviewPlan { + preview: PartialPreviewPlan, + every_pass: bool, + samples_per_pixel: u32, + budget: CpuBudget, + total_commits: u64, + quota_limit: u32, +} +impl ProtectedPreviewPlan { + pub fn new(source_width: u32, source_height: u32, samples_per_pixel: u32, budget: CpuBudget) -> Result { + Self::with_cadence(source_width, source_height, samples_per_pixel, budget, true) + } + pub(crate) fn with_cadence(source_width: u32, source_height: u32, samples_per_pixel: u32, budget: CpuBudget, every_pass: bool) -> Result { + budget.validate_image(source_width, source_height, Some(CpuProgressiveOptions { samples_per_pixel, seed: 0 }))?; + let preview = PartialPreviewPlan::new(source_width, source_height)?; + let total_commits = u64::from(source_width) + .checked_mul(u64::from(source_height)) + .and_then(|v| v.checked_mul(u64::from(samples_per_pixel))) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected camera-commit count overflow"))?; + let pixels = u64::from(source_width) * u64::from(source_height); + let early = + u32::try_from(pixels.saturating_sub(1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early quota overflow"))?; + let quota_limit = if every_pass { + early.checked_add(samples_per_pixel - 1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))? + } else { + u32::try_from(total_commits.saturating_sub(1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))? + }; + let plan = Self { preview, every_pass, samples_per_pixel, budget, total_commits, quota_limit }; + plan.aggregate_limit()?; + Ok(plan) + } + pub fn validate(&self) -> Result<()> { + if *self != Self::with_cadence(self.preview.source_width(), self.preview.source_height(), self.samples_per_pixel, self.budget, self.every_pass)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan differs from its canonical policy")); + } + Ok(()) + } + pub fn preview_plan(&self) -> PartialPreviewPlan { + self.preview + } + pub fn samples_per_pixel(&self) -> u32 { + self.samples_per_pixel + } + pub fn budget(&self) -> CpuBudget { + self.budget + } + pub fn total_commits(&self) -> u64 { + self.total_commits + } + pub fn ordinary_limit(&self) -> u64 { + self.budget.limits().max_work_units + } + pub fn quota_limit(&self) -> u32 { + self.quota_limit + } + pub fn snapshot_work(&self) -> Result { + self.preview.snapshot_work() + } + pub fn presentation_limit(&self) -> Result { + self.snapshot_work()? + .checked_mul(u64::from(self.quota_limit)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected presentation allowance overflow")) + } + pub fn aggregate_limit(&self) -> Result { + self.ordinary_limit() + .checked_add(self.presentation_limit()?) + .filter(|v| *v <= MAX_PROTECTED_CPU_WORK) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected aggregate work exceeds its explicit ceiling")) + } + /// Number of reached milestones in O(1), including a final sentinel without + /// adding a final-image snapshot. A delayed consumer cannot create a long + /// uninterruptible coalescing loop in the worker. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn reached_milestones(&self, committed: u64) -> Result { + if committed > self.total_commits { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected frontier exceeds its final target")); + } + if !self.every_pass { + if committed == 0 || self.quota_limit == 0 { + return Ok(0); + } + if committed >= self.total_commits - 1 || self.quota_limit == 1 { + return Ok(self.quota_limit); + } + return committed + .checked_mul(u64::from(self.quota_limit - 1)) + .map(|n| n.div_ceil(self.total_commits - 2)) + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n <= self.quota_limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected legacy reached quota overflow")); + } + let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); + let early = pixels.saturating_sub(1).min(64); + let reached_early = if committed == 0 || early == 0 { + 0 + } else if committed >= pixels - 1 { + early + } else if early == 1 { + 1 + } else { + committed + .checked_mul(early - 1) + .map(|n| n.div_ceil(pixels - 2)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected reached milestone overflow"))? + }; + let passes = (committed / pixels).min(u64::from(self.samples_per_pixel - 1)); + reached_early + .checked_add(passes) + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| *n <= self.quota_limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected reached quota overflow")) + } + + /// Zero-based, strictly increasing milestones below the final target. + pub fn milestone(&self, index: u32) -> Result { + if index >= self.quota_limit { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected milestone index outside its quota")); + } + if !self.every_pass { + if self.quota_limit == 1 { + return Ok(1); + } + return self.total_commits + .checked_sub(2) + .and_then(|n| n.checked_mul(u64::from(index))) + .and_then(|n| n.checked_div(u64::from(self.quota_limit - 1))) + .and_then(|n| n.checked_add(1)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected legacy milestone overflow")); + } + let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); + let early = u32::try_from(pixels.saturating_sub(1).min(64)) + .map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early milestone overflow"))?; + if index < early { + if early == 1 { + return Ok(1); + } + return pixels + .checked_sub(2) + .and_then(|n| n.checked_mul(u64::from(index))) + .and_then(|n| n.checked_div(u64::from(early - 1))) + .and_then(|n| n.checked_add(1)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected early milestone arithmetic overflow")); + } + u64::from(index - early + 1) + .checked_mul(pixels) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected pass milestone arithmetic overflow")) + } +} + +/// Actual admitted policy and monotonic producer usage; never a saved design field. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct ProtectedPreviewReport { + pub policy_version: u32, + pub ordinary_limit: u64, + pub presentation_limit: u64, + pub aggregate_limit: u64, + pub ordinary_used: u64, + pub presentation_used: u64, + pub accepted_snapshots: u32, + pub quota_limit: u32, + pub next_milestone_index: u32, + pub quota_exhausted: bool, + pub milestones_complete: bool, +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/png.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/png.rs new file mode 100644 index 000000000..f260940e8 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/png.rs @@ -0,0 +1,164 @@ +//! Bounded PNG encoding shared by native image executors. +use super::{CancelToken, ErrorCode, ImageRequest, ImageWork, JobError, Phase, Progress, Result, TaskPoll}; +use std::{ + io::Write, + sync::{Arc, Mutex}, +}; + +struct Output { + bytes: Arc>>, + limit: usize, + cancel: CancelToken, +} +impl Write for Output { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.cancel.is_cancelled() { + return Err(std::io::Error::other("render cancelled")); + } + let mut out = self.bytes.lock().map_err(|_| std::io::Error::other("PNG lock poisoned"))?; + if out.len().checked_add(bytes.len()).is_none_or(|n| n > self.limit) { + return Err(std::io::Error::other("PNG byte limit exceeded")); + } + out.try_reserve_exact(bytes.len()).map_err(|_| std::io::Error::other("PNG allocation failed"))?; + out.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Owns admitted RGBA bytes and yields after at most four scanlines. +pub struct PngTask { + rgba: Vec, + row: usize, + width: usize, + height: usize, + bytes: Arc>>, + writer: Option>, + cancel: CancelToken, +} +impl PngTask { + pub fn new(request: &ImageRequest, rgba: Vec, cancel: CancelToken) -> Result { + let pixels = u64::from(request.width) * u64::from(request.height); + if request.width == 0 + || request.height == 0 + || u64::from(request.width) > super::GPU_PATH_LIMITS.max_dimension + || u64::from(request.height) > super::GPU_PATH_LIMITS.max_dimension + || pixels > super::GPU_PATH_LIMITS.max_pixels + || rgba.len() as u64 != pixels * 4 + { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length")); + } + cancel.check()?; + Self::new_with_limits(request, rgba, cancel, super::GPU_PATH_LIMITS) + } + pub(crate) fn new_with_limits(request: &ImageRequest, rgba: Vec, cancel: CancelToken, limits: crate::RenderLimits) -> Result { + let pixels = super::linear_exr::output_pixels_with_limits(request.width, request.height, limits)?; + let rgba_bytes = super::linear_exr::checked_output_bytes(pixels, 4, 0, limits)?; + if rgba.len() != rgba_bytes { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length")); + } + let limit = super::linear_exr::checked_output_bytes(pixels, 8, 65_536, limits)?; + let retained = super::linear_exr::checked_output_bytes(rgba.capacity() as u64, 1, 0, limits)? as u64; + super::linear_exr::checked_stage_bytes(1, retained, limit as u64, limits)?; + cancel.check()?; + let bytes = Arc::new(Mutex::new(Vec::new())); + let output = Output { bytes: bytes.clone(), limit, cancel: cancel.clone() }; + let mut encoder = png::Encoder::new(output, request.width, request.height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual); + let writer = encoder.write_header().and_then(|w| w.into_stream_writer()).map_err(encoding)?; + Ok(Self { rgba, row: 0, width: request.width as usize, height: request.height as usize, bytes, writer: Some(writer), cancel }) + } +} +fn encoding(e: impl std::fmt::Display) -> JobError { + JobError::new(ErrorCode::EncodingFailed, e.to_string()) +} +impl ImageWork for PngTask { + fn step(&mut self, _units: usize) -> Result { + self.cancel.check()?; + for _ in 0..4 { + if self.row == self.height { + break; + } + let start = self.row * self.width * 4; + let row = self.rgba.get(start..start + self.width * 4).ok_or_else(|| encoding("missing PNG row"))?; + self.writer.as_mut().ok_or_else(|| encoding("PNG already completed"))?.write_all(row).map_err(encoding)?; + self.row += 1; + } + if self.row != self.height { + return Ok(TaskPoll::Pending(Progress { phase: Phase::Encoding, done: self.row as u64, total: self.height as u64 })); + } + self.writer.take().ok_or_else(|| encoding("PNG already completed"))?.finish().map_err(encoding)?; + self.cancel.check()?; + let mut bytes = self.bytes.lock().map_err(|_| encoding("PNG lock poisoned"))?; + Ok(TaskPoll::Complete(std::mem::take(&mut *bytes))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(width: u32, height: u32) -> ImageRequest { + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + width, + height, + camera: Default::default(), + integrator: Default::default(), + raytrace: None, + environment: None, + textures: None, + studio_weights: None, + background: [0; 3], + transparent_background: false, + } + } + fn finish(mut task: PngTask) -> Vec { + loop { + if let TaskPoll::Complete(bytes) = task.step(1).unwrap() { + return bytes; + } + } + } + + #[test] + fn explicit_png_keeps_default_bytes_and_roundtrips_a_narrow_wide_image() { + let small = request(3, 2); + let rgba = [20, 40, 60, 255].repeat(6); + let legacy = finish(PngTask::new(&small, rgba.clone(), CancelToken::default()).unwrap()); + let explicit = finish(PngTask::new_with_limits(&small, rgba, CancelToken::default(), super::super::GPU_PATH_LIMITS).unwrap()); + assert_eq!(explicit, legacy); + let wide = request(8193, 1); + let rgba = [20, 40, 60, 255].repeat(8193); + assert!(PngTask::new(&wide, vec![], CancelToken::default()).is_err()); + let png = finish( + PngTask::new_with_limits(&wide, rgba.clone(), CancelToken::default(), super::super::CpuBudget::Workstation.image_limits(false)).unwrap(), + ); + let decoded = image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (8193, 1)); + assert_eq!(decoded.as_raw(), &rgba); + } + + #[test] + fn png_dimension_length_and_cancel_precedence_remains_legacy() { + let cancel = CancelToken::default(); + cancel.cancel(); + assert_eq!(PngTask::new(&request(0, 1), vec![], cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(PngTask::new(&request(1, 1), vec![], cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(PngTask::new(&request(1, 1), vec![0; 4], cancel.clone()).err().unwrap().code, ErrorCode::Cancelled); + let bad = crate::RenderLimits { max_scratch_bytes: u64::MAX, ..super::super::GPU_PATH_LIMITS }; + assert!(PngTask::new_with_limits(&request(1, 1), vec![0; 4], CancelToken::default(), bad).is_err()); + let cancel = CancelToken::default(); + let mut task = PngTask::new_with_limits(&request(1, 1), vec![0; 4], cancel.clone(), super::super::GPU_PATH_LIMITS).unwrap(); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/regrade.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/regrade.rs new file mode 100644 index 000000000..82a377751 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/regrade.rs @@ -0,0 +1,218 @@ +//! Cancellable, geometry-free presentation of an immutable native linear master. +//! A derivative retains the original frame lease instead of copying EXR bytes. +use super::{CancelToken, ErrorCode, ImageRequest, ImageWork, JobError, Phase, PngTask, Progress, RenderFrame, Result, TaskPoll}; +use super::{bloom::BloomTask, linear_exr_decode::Decoder, presentation::Presentation}; +use std::sync::Arc; + +pub(super) fn required_bytes(source: &RenderFrame, settings: Presentation) -> Result { + settings.validate()?; + super::linear_exr::encoded_limit(source.info.width, source.info.height)?; + required_bytes_with_limits(source, settings, super::GPU_PATH_LIMITS) +} + +pub(crate) fn required_bytes_with_limits(source: &RenderFrame, settings: Presentation, limits: crate::RenderLimits) -> Result { + settings.validate()?; + super::linear_exr::encoded_limit_with_limits(source.info.width, source.info.height, limits)?; + if source.linear_exr().is_none() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this completed frame has no retained raw linear master")); + } + output_bytes(source.info.width, source.info.height, settings, limits) +} + +fn output_bytes(width: u32, height: u32, settings: Presentation, limits: crate::RenderLimits) -> Result { + let pixels = super::linear_exr::output_pixels_with_limits(width, height, limits)?; + let photo = settings.finishing.photographic.scratch_bytes_with_limits(width, height, limits)?; + let extra = photo.checked_add(1_048_576).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "regrade byte estimate overflow"))?; + super::linear_exr::checked_stage_bytes(pixels, 48, extra, limits) +} + +pub(super) struct RegradeTask { + source: Arc, + settings: Presentation, + limits: crate::RenderLimits, + cancel: CancelToken, + decoder: Option, + bloom: Option, + linear: Option>, + glow: Option>, + rgba: Vec, + encoded: usize, + png: Option, + photographic: Option, +} +impl RegradeTask { + pub(super) fn new(source: Arc, settings: Presentation, cancel: CancelToken) -> Result { + required_bytes(&source, settings)?; + Self::new_with_limits(source, settings, cancel, super::GPU_PATH_LIMITS) + } + pub(crate) fn new_with_limits( + source: Arc, + settings: Presentation, + cancel: CancelToken, + limits: crate::RenderLimits, + ) -> Result { + required_bytes_with_limits(&source, settings, limits)?; + let raw = source.linear_exr().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "linear master disappeared"))?; + let decoder = if limits == super::GPU_PATH_LIMITS { + Decoder::new(raw, source.info.width, source.info.height, &cancel)? + } else { + Decoder::new_with_limits(raw, source.info.width, source.info.height, &cancel, limits)? + }; + Ok(Self { + source, + settings, + limits, + cancel, + decoder: Some(decoder), + bloom: None, + linear: None, + glow: None, + rgba: Vec::new(), + encoded: 0, + png: None, + photographic: None, + }) + } + pub(super) fn source(&self) -> Arc { + self.source.clone() + } + fn pending(&self, done: u64, total: u64) -> Result { + Ok(TaskPoll::Pending(Progress { phase: Phase::Encoding, done, total })) + } +} +impl ImageWork for RegradeTask { + fn step(&mut self, units: usize) -> Result { + self.cancel.check()?; + if let Some(png) = &mut self.png { + return png.step(units); + } + let (width, height) = (self.source.info.width, self.source.info.height); + if let Some(mut task) = self.photographic.take() { + if !task.step(units)? { + let (done, total) = task.progress(); + self.photographic = Some(task); + return self.pending(done, total); + } + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width, + height, + camera: Default::default(), + integrator: Default::default(), + raytrace: None, + environment: None, + textures: None, + background: self.settings.background, + transparent_background: self.settings.transparent_background, + }; + self.png = Some(PngTask::new_with_limits(&request, task.finish()?, self.cancel.clone(), self.limits)?); + return self.pending(0, u64::from(height)); + } + if let Some(mut decoder) = self.decoder.take() { + let raw = self.source.linear_exr().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing retained master"))?; + if !decoder.step(raw, &self.cancel)? { + let done = decoder.rows(); + self.decoder = Some(decoder); + return self.pending(done, u64::from(height)); + } + let pixels = decoder.finish()?; + if let Some(bloom) = self.settings.finishing.bloom.filter(|b| b.active()) { + self.bloom = Some(BloomTask::new_with_limits(width, height, pixels, bloom, self.cancel.clone(), self.limits)?); + return self.pending(0, u64::from(height) * 7); + } + self.linear = Some(pixels); + } + if let Some(mut bloom) = self.bloom.take() { + if !bloom.step(4)? { + let (done, total) = (bloom.completed_lines(), bloom.total_lines()); + self.bloom = Some(bloom); + return self.pending(done, total); + } + let (pixels, glow) = bloom.finish()?; + self.linear = Some(pixels); + self.glow = Some(glow); + } + let count = width as usize * height as usize; + if self.rgba.is_empty() { + self.rgba.try_reserve_exact(count * 4).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "regrade display allocation failed"))?; + if self.rgba.capacity() != count * 4 { + return Err(JobError::new(ErrorCode::LimitExceeded, "regrade display exceeds admitted capacity")); + } + self.rgba.resize(count * 4, 0); + } + let end = self.encoded.saturating_add(units.clamp(1, 4096)).min(count); + let pixels = self + .linear + .as_deref() + .and_then(|p| p.get(self.encoded..end)) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "missing regrade pixels"))?; + let output = self.rgba.get_mut(self.encoded * 4..end * 4).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing regrade output"))?; + let glow = self.glow.as_deref().and_then(|g| g.get(self.encoded..end)); + self.settings.display_with_limits(width, height, self.limits)?.encode_bloom_at_with_limits( + pixels, + output, + &self.cancel, + self.encoded, + glow, + self.limits, + )?; + self.encoded = end; + if end < count { + return self.pending(end as u64, count as u64); + } + self.glow = None; + if self.settings.finishing.photographic.active() { + let pixels = self.linear.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing photographic master pixels"))?; + self.photographic = Some(super::photographic::PhotographicTask::new_with_limits( + width, + height, + std::mem::take(&mut self.rgba), + pixels, + self.settings.finishing.photographic, + self.cancel.clone(), + self.limits, + )?); + return self.pending(0, u64::from(width) * u64::from(height)); + } + self.linear = None; + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width, + height, + camera: Default::default(), + integrator: Default::default(), + raytrace: None, + environment: None, + textures: None, + background: self.settings.background, + transparent_background: self.settings.transparent_background, + }; + self.png = Some(PngTask::new_with_limits(&request, std::mem::take(&mut self.rgba), self.cancel.clone(), self.limits)?); + self.pending(0, u64::from(height)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn regrade_size_estimate_is_explicit_checked_and_does_not_grant_a_lease() { + let wide = super::super::CpuBudget::Workstation.image_limits(false); + assert_eq!(output_bytes(8193, 1, Presentation::default(), wide).unwrap(), 8193 * 48 + 1_048_576); + assert!(output_bytes(8193, 1, Presentation::default(), super::super::GPU_PATH_LIMITS).is_err()); + assert!(output_bytes(u32::MAX, u32::MAX, Presentation::default(), wide).is_err()); + assert!(output_bytes(1, 1, Presentation::default(), crate::RenderLimits { max_scratch_bytes: u64::MAX, ..wide }).is_err()); + assert!(output_bytes(1, 1, Presentation::default(), crate::RenderLimits { max_scratch_bytes: 1_048_576, ..wide }).is_err()); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/rt2_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/rt2_tests.rs new file mode 100644 index 000000000..bcd6bb3e0 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/job/rt2_tests.rs @@ -0,0 +1,269 @@ +//! Runtime-option and admission regressions; no render timing assumptions. + +use super::*; +use crate::ProductScene; +use solidcraft_geom::Aabb3; + +fn request(integrator: Integrator) -> ImageRequest { + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator, + raytrace: None, + camera: Default::default(), + width: 16, + height: 16, + background: [0; 3], + transparent_background: false, + } +} + +#[test] +fn options_reject_retained_capacity_even_when_no_lights_are_active() { + let options = RaytraceOptions { lights: Some(Vec::with_capacity(64)), ..Default::default() }; + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + let serialized = serde_json::to_value(&options).unwrap(); + let decoded: RaytraceOptions = serde_json::from_value(serialized).unwrap(); + assert!(decoded.validate().is_ok(), "wire input retains no oversized source allocation"); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn raytrace_admission_validates_retained_options_before_cloning() { + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let mut request = request(Integrator::Raytrace); + request.raytrace = Some(RaytraceOptions { lights: Some(Vec::with_capacity(64)), ..Default::default() }); + let original = request.raytrace.as_ref().unwrap(); + assert_eq!(original.validate().unwrap_err().code, ErrorCode::InvalidRequest); + assert!(original.clone().validate().is_ok(), "cloning an empty Vec discards its retained capacity"); + let error = admit(&scene, &request).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(request.raytrace.as_ref().unwrap().lights.as_ref().unwrap().capacity(), 64); +} + +#[test] +fn options_preserve_the_eight_light_boundary_and_refuse_the_ninth() { + let light = serde_json::json!({"direction": [0.0, 0.0, -1.0], "color": [1.0, 1.0, 1.0], "intensity": 1.0}); + let accepted: RaytraceOptions = serde_json::from_value(serde_json::json!({"lights": vec![light.clone(); 8]})).unwrap(); + assert!(accepted.validate().is_ok()); + assert!(serde_json::from_value::(serde_json::json!({"lights": vec![light; 9]})).is_err()); +} + +#[test] +fn exposure_refuses_nonfinite_and_out_of_range_values() { + for exposure_ev in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -33.0, 33.0, -32.01, 32.01] { + let options = RaytraceOptions { exposure_ev, ..Default::default() }; + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + } + // CPU exposure now shares the saved/UI range; the old +/-16 refusal + // is superseded, not a reason to change any transport oracle. + assert_eq!(RaytraceOptions::default().exposure_ev, 0.0); + for exposure_ev in [-32.0, -17.0, -16.0, 0.0, 16.0, 17.0, 32.0] { + assert!(RaytraceOptions { exposure_ev, ..Default::default() }.validate().is_ok()); + } +} + +#[test] +fn rejected_raytrace_submission_leaves_existing_raster_reservation_intact() { + let host = CpuHost::cooperative(); + let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let raster = host.submit(JobId { session: 1, serial: 1, generation: 1 }, 1, scene(), request(Integrator::Raster)).unwrap(); + let before = host.admitted_bytes(); + assert!(before > 0); + let error = host.submit(JobId { session: 1, serial: 2, generation: 2 }, 1, scene(), request(Integrator::Raytrace)).err().unwrap(); + assert_eq!(error.code, ErrorCode::HostUnavailable); + assert_eq!(host.admitted_bytes(), before); + assert_eq!(raster.status().unwrap().progress.phase, Phase::Queued); + assert!(raster.frame().unwrap().is_none()); + assert_eq!(raster.cancel().unwrap().progress.phase, Phase::Cancelled); + // Pump only to discard cancelled queued input; it must not produce a frame. + assert!(!host.pump(1).unwrap()); + assert_eq!(host.admitted_bytes(), 0); + assert!(raster.frame().unwrap().is_none()); +} + +#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] +#[test] +fn native_integrators_share_one_host_and_retained_frame_budget() { + let mut host = CpuHost::for_platform().unwrap(); + let scene = || ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let raster_id = JobId { session: 10, serial: 1, generation: 1 }; + let raytrace_id = JobId { session: 20, serial: 1, generation: 1 }; + let raster = host.submit(raster_id, 100, scene(), request(Integrator::Raster)).unwrap(); + let raytrace = host.submit(raytrace_id, 200, scene(), request(Integrator::Raytrace)).unwrap(); + // Deadlock watchdog only; there is no rendering-speed assertion. + for job in [&raster, &raytrace] { + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + } + host.join_worker_for_test().unwrap(); + let raster_frame = raster.frame().unwrap().unwrap(); + let raytrace_frame = raytrace.frame().unwrap().unwrap(); + assert_eq!(raster_frame.info.job, raster_id); + assert_eq!(raytrace_frame.info.job, raytrace_id); + assert_eq!(raster_frame.info.scene_generation, 100); + assert_eq!(raytrace_frame.info.scene_generation, 200); + assert_eq!(raster_frame.info.executor.as_str(), "cpu-product"); + assert_eq!(raytrace_frame.info.executor.as_str(), "cpu-raytrace"); + let both = host.admitted_bytes(); + assert!(both > 0); + drop(raster); + drop(raytrace); + assert_eq!(host.admitted_bytes(), both, "external frames retain both leases"); + drop(raster_frame); + assert!(host.admitted_bytes() > 0 && host.admitted_bytes() < both); + drop(raytrace_frame); + assert_eq!(host.admitted_bytes(), 0); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn cancelled_raytrace_task_never_returns_a_frame() { + let cancel = CancelToken::default(); + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + let mut task = crate::raytrace::image::ImageTask::new(scene, request(Integrator::Raytrace), cancel.clone(), RaytraceOptions::default()).unwrap(); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); +} + +#[cfg(feature = "raytrace-cpu")] +#[test] +fn completed_raytrace_task_releases_captured_mesh_before_returning_png() { + let mesh = Arc::new(solidcraft_geom::Mesh::default()); + let captured = Arc::downgrade(&mesh); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "Lease probe".into(), + mesh, + color: [0; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds: Aabb3::EMPTY, + }; + let mut task = + crate::raytrace::image::ImageTask::new(scene, request(Integrator::Raytrace), CancelToken::default(), RaytraceOptions::default()).unwrap(); + assert!(captured.upgrade().is_some()); + let mut completed = false; + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = task.step(4).unwrap() { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + completed = true; + break; + } + } + assert!(completed, "bounded empty-scene fixture must complete"); + assert!(captured.upgrade().is_none(), "the host may shrink the lease as soon as Complete is returned, even while the task remains alive"); + assert_eq!(task.progress().phase, Phase::Completed); +} +#[test] +fn emission_runtime_json_is_bounded_explicit_and_roundtrips() { + use super::{EmissionSides, RaytraceOptions, SurfaceEmission}; + let emitter = SurfaceEmission { body_index: 0, body: "fixture".into(), color: [1.0, 0.5, 0.0], strength: 2.0, sides: EmissionSides::Front }; + let options = RaytraceOptions { emissions: Some(vec![emitter.clone()]), ..Default::default() }; + let encoded = serde_json::to_value(&options).unwrap(); + assert_eq!(serde_json::from_value::(encoded).unwrap(), options); + assert!(serde_json::from_str::("{\"emissions\":null}").is_err()); + assert!(serde_json::from_value::(serde_json::json!({"emissions": vec![emitter; 33]})).is_err()); + assert!( + serde_json::from_value::( + serde_json::json!({"emissions":[{"body_index":0,"body":"x".repeat(257),"color":[1,1,1],"strength":1}]}) + ) + .is_err() + ); + assert_eq!(serde_json::from_str::("{}").unwrap().emissions, None); + assert_eq!(serde_json::from_str::("{\"emissions\":[]}").unwrap().emissions, Some(Vec::new())); +} + +fn directional_options() -> RaytraceOptions { + RaytraceOptions { + directional_shadow_transmission: true, + dielectrics: vec![DielectricOptions { + body_index: 0, + body_name: "directional glass".into(), + boundary: DielectricBoundary::ThinSheet, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 1.0, + }], + ..Default::default() + } +} + +#[test] +fn directional_mode_is_explicit_false_omitted_and_true_roundtrips() { + let old_default = serde_json::json!({"reflections":null,"anisotropic_faces":[null,null],"preset":null,"exposure_ev":0.0,"shadows":true}); + let decoded: RaytraceOptions = serde_json::from_value(old_default.clone()).unwrap(); + assert!(!decoded.directional_shadow_transmission); + assert_eq!(serde_json::to_value(&decoded).unwrap(), old_default); + let mut explicit = old_default.clone(); + explicit["directional_shadow_transmission"] = serde_json::json!(false); + assert_eq!(serde_json::to_value(serde_json::from_value::(explicit).unwrap()).unwrap(), old_default); + let enabled = directional_options(); + enabled.validate().unwrap(); + let wire = serde_json::to_value(&enabled).unwrap(); + assert_eq!(wire["directional_shadow_transmission"], serde_json::json!(true)); + assert_eq!(serde_json::from_value::(wire).unwrap(), enabled); + for bad in [serde_json::json!(null), serde_json::json!(1), serde_json::json!("true")] { + let mut wire = old_default.clone(); + wire["directional_shadow_transmission"] = bad; + assert!(serde_json::from_value::(wire).is_err()); + } +} + +#[test] +fn directional_mode_refuses_incompatible_inputs_without_rewriting_legacy() { + for case in 0..7 { + let mut options = directional_options(); + match case { + 0 => options.shadows = false, + 1 => options.dielectrics = Vec::new(), + 2 => options.reflections = Some(ReflectionOptions { bodies: Vec::new(), max_bounces: 1, samples: 1 }), + 3 => { + options.anisotropic_faces[0] = Some(AnisotropicFaceOptions { + body_index: 0, + body_name: "directional glass".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: AnisotropicOrientation::QuarterTurn, + roughness_x: 0.2, + roughness_y: 0.5, + }) + } + 4 => options.environment = Some(RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + 5 => { + options.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]) + } + _ => { + options.area_lights = Some(vec![RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [1.0, 0.0, 0.0], + edge_v_mm: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }]) + } + } + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); + options.directional_shadow_transmission = false; + options.validate().unwrap(); + } + let mut empty_locals = directional_options(); + empty_locals.punctual_lights = Some(Vec::new()); + empty_locals.area_lights = Some(Vec::new()); + empty_locals.validate().unwrap(); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/anisotropic_faces_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/anisotropic_faces_tests.rs new file mode 100644 index 000000000..acce07f1c --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/anisotropic_faces_tests.rs @@ -0,0 +1,251 @@ +use super::*; +use crate::job::{AnisotropicFaceOptions, CancelToken, ImageRequest, Integrator, TaskPoll}; +use crate::{Camera, ProductMesh, StandardView}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn body(name: &str, x: f64) -> ProductMesh { + ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(x - 2.0, -2.0, 0.0), Vec3::new(x + 2.0, -2.0, 0.0), Vec3::new(x + 2.0, 2.0, 0.0), Vec3::new(x - 2.0, 2.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![7, 7], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.8, 0.8), 1.0, 0.5, 1.5).unwrap()), + faces: Vec::new(), + } +} + +fn scene() -> ProductScene { + let meshes = vec![body("left@occurrence", -5.0), body("right@occurrence", 0.0), body("scalar control@occurrence", 5.0)]; + let bounds = meshes.iter().map(|b| b.mesh.bounds()).reduce(|a, b| a.union(&b)).unwrap(); + ProductScene { meshes, bounds } +} + +fn options() -> RaytraceOptions { + let target = |body_index, name: &str, orientation| { + Some(AnisotropicFaceOptions { + body_index, + body_name: name.into(), + face: 7, + tangent: [1.0, 0.0, 0.0], + orientation, + roughness_x: 0.25, + roughness_y: 0.8, + }) + }; + RaytraceOptions { + anisotropic_faces: [ + target(0, "left@occurrence", AnisotropicOrientation::Zero), + target(1, "right@occurrence", AnisotropicOrientation::QuarterTurn), + ], + lights: Some(vec![job::DirectionalLightOptions { direction: [0.6, 0.0, 0.8], color: [1.0; 3], intensity: 1.0 }]), + shadows: false, + ..Default::default() + } +} + +#[test] +fn explicit_capture_identity_face_and_frame_are_required() { + let scene = scene(); + let baseline = options(); + assert!(prepare(&scene, &baseline, || Ok(())).is_ok()); + for change in 0..4 { + let mut options = baseline.clone(); + let target = options.anisotropic_faces[0].as_mut().unwrap(); + match change { + 0 => target.body_name = "wrong occurrence".into(), + 1 => target.body_index = 50, + 2 => target.face = 99, + _ => target.tangent = [0.0, 0.0, 1.0], + } + assert!(prepare(&scene, &options, || Ok(())).is_err()); + } +} + +#[test] +fn curved_inconsistent_missing_and_excessive_target_meshes_refuse() { + for change in 0..4 { + let mut scene = scene(); + let mesh = Arc::make_mut(&mut scene.meshes[0].mesh); + match change { + 0 => mesh.positions[3].z = 0.1, + 1 => mesh.triangles[1].swap(1, 2), + 2 => mesh.tri_face.clear(), + _ => { + mesh.triangles = vec![[0, 1, 2]; MAX_TARGET_BODY_TRIANGLES + 1]; + mesh.tri_face = vec![7; MAX_TARGET_BODY_TRIANGLES + 1]; + } + } + assert!(prepare(&scene, &options(), || Ok(())).is_err()); + } +} + +#[test] +fn bounded_dto_roundtrip_duplicates_and_original_capacity() { + let options = options(); + assert!(options.validate().is_ok()); + let encoded = serde_json::to_value(&options).unwrap(); + assert_eq!(serde_json::from_value::(encoded.clone()).unwrap(), options); + let expected = options.anisotropic_faces.iter().flatten().map(|t| t.body_name.capacity() as u64).sum::() + + options.lights.as_ref().unwrap().capacity() as u64 * std::mem::size_of::() as u64; + assert_eq!(options.retained_bytes().unwrap(), expected); + let mut duplicate = options.clone(); + duplicate.anisotropic_faces[1] = duplicate.anisotropic_faces[0].clone(); + assert!(duplicate.validate().is_err()); + let mut excessive_capacity = options.clone(); + let target = excessive_capacity.anisotropic_faces[0].as_mut().unwrap(); + let mut name = String::with_capacity(2048); + name.push_str(&target.body_name); + target.body_name = name; + assert!(excessive_capacity.retained_bytes().is_err()); + let mut excessive_array = encoded; + excessive_array["anisotropic_faces"] = serde_json::json!([null, null, null]); + assert!(serde_json::from_value::(excessive_array).is_err()); + assert!(serde_json::from_value::(serde_json::json!({"anisotropic_faces":[{"body_index":0,"body_name":"x".repeat(1025),"face":7,"tangent":[1,0,0],"orientation":"zero","roughness_x":0.25,"roughness_y":0.8},null]})).is_err()); + assert!(serde_json::from_value::(serde_json::json!({"environment":{}})).is_err()); +} + +#[test] +fn target_certification_uses_caller_work_and_cancellation() { + let mut charged = 0; + prepare(&scene(), &options(), || { + charged += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(charged, 4); + let error = prepare(&scene(), &options(), || Err(JobError::new(ErrorCode::Cancelled, "cancelled"))).err().unwrap(); + assert_eq!(error.code, ErrorCode::Cancelled); + let error = prepare(&scene(), &options(), || Err(JobError::new(ErrorCode::LimitExceeded, "same work budget"))).err().unwrap(); + assert_eq!(error.code, ErrorCode::LimitExceeded); +} + +#[test] +fn direct_response_respects_geometry_visibility_and_quarter_turn() { + let scene = scene(); + let options = options(); + let targets = prepare(&scene, &options, || Ok(())).unwrap(); + let lights = + Lighting::new(vec![super::super::lighting::DirectionalLight::new(Vec3::new(0.6, 0.0, 0.8), Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap()]).unwrap(); + let surface = scene.meshes[0].surface.unwrap(); + let first = targets[0].unwrap().shade(&lights, surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + let turned = targets[1].unwrap().shade(&lights, surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(); + assert!(turned.x > first.x + 0.1); + assert_eq!(targets[0].unwrap().shade(&lights, surface, Vec3::Z, Vec3::Z, |_, _| Ok(false)).unwrap(), Vec3::ZERO); + assert_eq!(targets[0].unwrap().shade(&lights, surface, Vec3::Z, -Vec3::Z, |_, _| Ok(true)).unwrap(), Vec3::ZERO); +} + +#[test] +fn decoded_cpu_png_rotates_only_the_two_explicit_planar_targets() { + fn render(scene: ProductScene, camera: Camera, options: RaytraceOptions) -> ::image::RgbaImage { + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(options.clone()), + camera, + width: 64, + height: 32, + background: [10, 20, 30], + transparent_background: false, + }; + let mut task = super::super::image::ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8(); + } + } + panic!("bounded planar anisotropic PNG fixture failed to finish"); + } + let scene = scene(); + let original = scene.meshes.iter().map(|b| b.mesh.positions.clone()).collect::>(); + let mut camera = Camera::default(); + camera.set_view(StandardView::Top); + camera.fit(&scene.bounds); + let first = render(scene.clone(), camera, options()); + let mut rotated = options(); + rotated.anisotropic_faces[0].as_mut().unwrap().orientation = AnisotropicOrientation::QuarterTurn; + rotated.anisotropic_faces[1].as_mut().unwrap().orientation = AnisotropicOrientation::Zero; + let second = render(scene.clone(), camera, rotated); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + for (index, x) in [-5.0, 0.0, 5.0].into_iter().enumerate() { + let (sx, sy, _) = camera.to_screen(Vec3::new(x, 0.0, 0.0), 64.0, 32.0, radius).unwrap(); + let a = first.get_pixel(sx.floor() as u32, sy.floor() as u32).0; + let b = second.get_pixel(sx.floor() as u32, sy.floor() as u32).0; + assert_ne!(a, [10, 20, 30, 255], "target centre missed fixture geometry"); + if index < 2 { + assert!(i16::from(a[0]).abs_diff(i16::from(b[0])) > 20, "selected face failed to rotate: {a:?} {b:?}"); + } else { + assert_eq!(a, b, "unselected scalar control changed"); + } + } + assert_eq!(first.get_pixel(0, 0).0, [10, 20, 30, 255]); + assert_eq!(first.get_pixel(0, 0), second.get_pixel(0, 0)); + assert_eq!(original, scene.meshes.iter().map(|b| b.mesh.positions.clone()).collect::>()); +} + +#[test] +fn reflection_bridge_preserves_anisotropic_pdf_weight_and_visual_rotation() { + let targets = prepare(&scene(), &options(), || Ok(())).unwrap(); + let surface = scene().meshes[0].surface.unwrap(); + let a = targets[0].unwrap().sample(surface, Vec3::Z, Vec3::Z, [0.4, 0.2]).unwrap().unwrap(); + let b = targets[1].unwrap().sample(surface, Vec3::Z, Vec3::Z, [0.4, 0.2]).unwrap().unwrap(); + let core = AnisotropicSurface::new(surface.base_color(), surface.metallic(), 0.25, 0.8, surface.dielectric_ior()).unwrap(); + // Production now proposes visible normals. Keep the exact bridge equality + // checks; the legacy NDF has separate unchanged numerical controls. + let reference = core.sample_visible_reflection(VisualFrame::new(Vec3::Z, Vec3::X).unwrap(), Vec3::Z, Vec3::Z, [0.4, 0.2]).unwrap().unwrap(); + assert_eq!(a.direction, reference.direction); + assert_eq!(a.pdf, reference.pdf); + assert_eq!(a.weight, reference.weight); + assert!((b.direction - Vec3::new(-a.direction.y, a.direction.x, a.direction.z)).len() < 1e-13); + assert!((b.pdf - a.pdf).abs() < 1e-13); + assert!( + (core.brdf(VisualFrame::new(Vec3::Z, Vec3::X).unwrap(), Vec3::Z, Vec3::Z, a.direction).unwrap() + - core.brdf(VisualFrame::new(Vec3::Z, Vec3::X).unwrap(), Vec3::Z, a.direction, Vec3::Z).unwrap()) + .len() + < 1e-13 + ); +} + +#[test] +fn equal_axes_use_the_existing_isotropic_samples_and_null_mass() { + let mut options = options(); + for input in options.anisotropic_faces.iter_mut().flatten() { + input.roughness_x = 1.0; + input.roughness_y = 1.0; + } + let targets = prepare(&scene(), &options, || Ok(())).unwrap(); + let surface = scene().meshes[0].surface.unwrap(); + let isotropic = OpaqueSurface::new(surface.base_color(), surface.metallic(), 1.0, surface.dielectric_ior()).unwrap(); + let mut accepted = 0; + for i in 0..1024 { + let u = [(i as f64 + 0.5) / 1024.0, 0.3]; + let a = targets[0].unwrap().sample(surface, Vec3::Z, Vec3::Z, u).unwrap(); + let b = super::super::reflection::rough_specular(isotropic, Vec3::Z, Vec3::Z, u).unwrap(); + match (a, b) { + (Some(a), Some(b)) => { + accepted += 1; + assert_eq!(a.direction, b.direction); + assert_eq!(a.pdf, b.pdf); + assert_eq!(a.weight, b.weight); + assert!((a.pdf - 1.0 / (4.0 * std::f64::consts::PI)).abs() < 1e-13); + } + (None, None) => {} + _ => panic!("isotropic sample/null mismatch"), + } + } + assert_eq!(accepted, 512); // Remaining half is null, never renormalized. +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs new file mode 100644 index 000000000..2d7e883ef --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs @@ -0,0 +1,322 @@ +use super::*; +use crate::job::{AnisotropicFaceOptions, AnisotropicOrientation, ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::{ProductMesh, StandardView}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn scene() -> ProductScene { + let reflector = ProductMesh { + transmission: None, + name: "explicit planar reflector".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0), Vec3::new(-20.0, 20.0, 20.0)], + normals: vec![super::super::unit(Vec3::new(0.0, -1.0, 1.0)).unwrap(); 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![7, 7], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.8, 0.8), 1.0, 0.4, 1.5).unwrap()), + faces: Vec::new(), + }; + let object = ProductMesh { + transmission: None, + name: "off-axis orange object".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-3.0, -12.0, 10.0), Vec3::new(-3.0, 12.0, 10.0), Vec3::new(3.0, 12.0, 10.0), Vec3::new(3.0, -12.0, 10.0)], + normals: vec![-Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [240, 80, 20], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }; + let meshes = vec![reflector, object]; + let bounds = meshes.iter().map(|b| b.mesh.bounds()).reduce(|a, b| a.union(&b)).unwrap(); + ProductScene { meshes, bounds } +} + +fn request(orientation: AnisotropicOrientation, reflect: bool) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Front); + let target = AnisotropicFaceOptions { + body_index: 0, + body_name: "explicit planar reflector".into(), + face: 7, + tangent: [1.0, 0.0, 0.0], + orientation, + roughness_x: 0.2, + roughness_y: 0.55, + }; + let options = RaytraceOptions { + anisotropic_faces: [Some(target), None], + reflections: reflect.then(|| ReflectionOptions { + bodies: vec![ReflectionBody { body: "explicit planar reflector".into(), mode: ReflectionMode::RoughSpecular }], + max_bounces: 1, + samples: 64, + }), + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, -1.0], color: [1.0; 3], intensity: 2.0 }]), + shadows: false, + ..Default::default() + }; + ImageRequest { + cpu_progressive_every_pass: true, + 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(options), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + } +} + +fn render(request: ImageRequest) -> [u8; 4] { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0; + } + } + panic!("bounded reflected scene PNG did not finish"); +} + +#[test] +fn actual_reflected_object_changes_with_the_selected_planar_orientation() { + let baseline = render(request(AnisotropicOrientation::Zero, false)); + assert_eq!(baseline, [0, 0, 0, 255]); // Light is below the reflector; no direct term. + let a = render(request(AnisotropicOrientation::Zero, true)); + let b = render(request(AnisotropicOrientation::QuarterTurn, true)); + assert!(a[0] > a[1] && a[1] > a[2], "actual orange object must contribute via a secondary hit: {a:?}"); + assert_ne!(a, b, "rotation must affect actual reflected scene transport"); + assert_eq!(a, render(request(AnisotropicOrientation::Zero, true))); +} + +fn union_environment() -> crate::lighting::environment_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]); + } + crate::lighting::environment_input::EnvironmentInput::new(crate::lighting::HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap() +} + +fn secondary_union(orientation: AnisotropicOrientation, intensity: f64) -> ImageTask { + let mut req = request(orientation, true); + let options = req.raytrace.as_mut().unwrap(); + options.lights = Some(Vec::new()); + options.punctual_lights = Some(vec![job::PunctualLightOptions { + position_mm: [0.0, 0.0, -10.0], + color: [1.0; 3], + intensity, + reference_distance_mm: 20.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + job::led_strip::LedStripOptions { + center_mm: [0.0, 0.0, -10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, 1.0, 0.0], + color: [1.0; 3], + intensity, + } + .append_to(options, 4) + .unwrap(); + ImageTask::new_with_environment(scene(), req.clone(), CancelToken::default(), req.raytrace.unwrap(), Some(union_environment())).unwrap() +} + +fn render_secondary_union(mut task: ImageTask, units: usize) -> (Vec, bool, bool, bool) { + let mut reset = false; + let mut point = false; + let mut area = false; + for _ in 0..500_000 { + if let Some(p) = task.pending.as_ref().filter(|p| p.bounce == 1) { + if p.hit.is_none() { + assert_eq!(p.punctual_index, 0); + assert_eq!(p.area_light, 0); + assert_eq!(p.area_index, 0); + assert!(!p.punctual_shadow && !p.punctual_ready && !p.area_shadow && !p.area_ready); + assert_eq!(p.punctual_value, Vec3::ZERO); + assert_eq!(p.area_value, Vec3::ZERO); + reset = true; + } else { + point |= p.punctual_value.len2() > 0.0; + area |= p.area_value.len2() > 0.0; + } + } + if let TaskPoll::Complete(png) = task.step(units).unwrap() { + return (png, reset, point, area); + } + } + panic!("bounded HDR/anisotropic secondary union did not finish"); +} + +#[test] +fn hdr_anisotropic_secondary_point_led_reset_and_partition_are_real_consumer_events() { + let (lit, reset, point, area) = render_secondary_union(secondary_union(AnisotropicOrientation::Zero, 4.0), 1); + assert!(reset && point && area, "secondary light state was not reset and consumed"); + let (dark, _, _, _) = render_secondary_union(secondary_union(AnisotropicOrientation::Zero, 0.0), 1); + let rgb = |png: &[u8]| ::image::load_from_memory(png).unwrap().to_rgba8().get_pixel(0, 0).0; + let a = rgb(&lit); + let b = rgb(&dark); + assert!(a[0] > b[0] && a[0] > a[1] && a[1] > a[2], "secondary direct lights must add orange response: {a:?} vs {b:?}"); + let (partitioned, _, _, _) = render_secondary_union(secondary_union(AnisotropicOrientation::Zero, 4.0), 128); + assert_eq!(lit, partitioned); + let (rotated, _, _, _) = render_secondary_union(secondary_union(AnisotropicOrientation::QuarterTurn, 4.0), 1); + assert_ne!(lit, rotated); +} + +#[test] +fn equal_axes_in_the_image_consumer_match_isotropic_reflection_bytes() { + let mut isotropic = request(AnisotropicOrientation::Zero, true); + isotropic.raytrace.as_mut().unwrap().anisotropic_faces = [None, None]; + let expected = render(isotropic); + for orientation in [AnisotropicOrientation::Zero, AnisotropicOrientation::QuarterTurn] { + let mut explicit = request(orientation, true); + let target = explicit.raytrace.as_mut().unwrap().anisotropic_faces[0].as_mut().unwrap(); + target.roughness_x = 0.4; + target.roughness_y = 0.4; + assert_eq!(render(explicit), expected); + } +} + +#[test] +fn mirrors_missing_or_ambiguous_reflection_targets_refuse_before_pixels() { + for kind in 0..3 { + let mut scene = scene(); + let mut request = request(AnisotropicOrientation::Zero, true); + let reflection = &mut request.raytrace.as_mut().unwrap().reflections.as_mut().unwrap().bodies[0]; + match kind { + 0 => reflection.mode = ReflectionMode::Mirror, + 1 => reflection.body = "missing".into(), + _ => scene.meshes[1].name = "explicit planar reflector".into(), + } + assert!(admit(&scene, &request, request.raytrace.as_ref().unwrap()).is_err()); + } +} + +#[test] +fn secondary_anisotropic_traversal_shares_job_work_and_cancellation() { + for cancel_now in [true, false] { + let request = request(AnisotropicOrientation::Zero, true); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + reached = true; + break; + } + } + assert!(reached, "actual consumer never continued the sampled anisotropic ray"); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } +} + +#[test] +fn primary_last_shadow_and_reflected_continuations_each_charge_at_most_one_unit() { + for shadows in [false, true] { + let mut request = request(AnisotropicOrientation::Zero, true); + request.raytrace.as_mut().unwrap().shadows = shadows; + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..10_000 { + if task.bvh.is_some() { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(task.bvh.is_some()); + let mut primary = false; + let mut last_shadow = false; + let mut secondary = false; + let mut secondary_hit = false; + let mut secondary_terminal = false; + for _ in 0..200_000 { + if task.pixel == 1 { + break; + } + let before_work = task.work.used(); + let before_sample = task.sample; + let before = task.pending.as_ref().map(|p| (p.bounce, p.hit.is_some(), p.light)); + task.pixel_one().unwrap(); + assert!(task.work.used() - before_work <= 1, "one pixel continuation consumed traversal and shading work together"); + let after = task.pending.as_ref().map(|p| (p.bounce, p.hit.is_some(), p.light)); + primary |= matches!(before, Some((0, false, _))) && matches!(after, Some((0, true, _))); + last_shadow |= shadows && matches!(before, Some((_, true, 0))) && matches!(after, Some((_, true, 1))); + secondary |= after.is_some_and(|(bounce, _, _)| bounce > 0); + secondary_hit |= before.is_some_and(|(bounce, hit, _)| bounce > 0 && !hit) && after.is_some_and(|(bounce, hit, _)| bounce > 0 && hit); + secondary_terminal |= before.is_some_and(|(bounce, _, _)| bounce > 0) && (task.sample != before_sample || task.pixel == 1); + } + assert_eq!(task.pixel, 1); + assert!(primary && secondary && secondary_hit && secondary_terminal); + assert!(!shadows || last_shadow); + } + // The public poll groups at most four of those continuations. + let request = request(AnisotropicOrientation::Zero, true); + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..10_000 { + if task.bvh.is_some() { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + let mut completed = false; + for _ in 0..200_000 { + let before = task.work.used(); + let poll = task.step(4).unwrap(); + assert!(task.work.used() - before <= 4); + if matches!(poll, TaskPoll::Complete(_)) { + completed = true; + break; + } + } + assert!(completed); +} + +#[test] +fn cancellation_after_last_shadow_is_seen_before_shading_or_sampling() { + for secondary in [false, true] { + let mut request = request(AnisotropicOrientation::Zero, true); + request.raytrace.as_mut().unwrap().shadows = true; + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light == task.lights.lights().len() && (p.bounce > 0) == secondary) { + reached = true; + break; + } + } + assert!(reached && task.pixels.is_empty()); + let before_sample = task.sample; + cancel.cancel(); + assert_eq!(task.pixel_one().err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.sample, before_sample); + assert!(task.pixels.is_empty()); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/deterministic_primary_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/deterministic_primary_tests.rs new file mode 100644 index 000000000..2a1ce6cea --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/deterministic_primary_tests.rs @@ -0,0 +1,626 @@ +use super::*; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn environment() -> 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, 4).unwrap() +} + +fn scene(face_override: bool) -> ProductScene { + let mut meshes = Vec::new(); + for (name, x) in [("Visible", 0.0), ("Hidden", 1000.0)] { + let mesh = Mesh { + positions: vec![ + Vec3::new(x - 20.0, -20.0, 0.0), + Vec3::new(x + 20.0, -20.0, 0.0), + Vec3::new(x + 20.0, 20.0, 0.0), + Vec3::new(x - 20.0, 20.0, 0.0), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + meshes.push(crate::ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(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(), + }); + } + if face_override { + meshes[0].faces.push(crate::FaceAppearance { + transmission: None, + face: 0, + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 1.0, 1.0, 1.5).unwrap()), + }); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + ProductScene { meshes, bounds } +} + +fn task(samples: u8, selected: bool, face_override: bool, shadows: bool) -> ImageTask { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + shadows, + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: if selected { "Visible" } else { "Hidden" }.into(), mode: ReflectionMode::RoughSpecular }], + max_bounces: 2, + samples, + }), + ..Default::default() + }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + 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(options.clone()), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + }; + ImageTask::new_with_environment(scene(face_override), request, CancelToken::default(), options, Some(environment())).unwrap() +} + +fn render(mut task: ImageTask, revoke_fixed_primary_proof: bool) -> (Vec, u64, usize) { + let mut primaries = 0; + for _ in 0..200_000 { + // Test-only reference: revoking the generator proof keeps the original R + // path/accumulation. No product switch, sampler, work limit or input changes. + if revoke_fixed_primary_proof && let Some(p) = task.pending.as_mut() { + p.repeatable_primary = false; + } + let absent = task.pending.is_none(); + match task.step(1).unwrap() { + TaskPoll::Complete(png) => return (png, task.work.used(), primaries), + TaskPoll::Pending(_) => { + if absent && task.pending.is_some() { + primaries += 1; + } + } + } + } + panic!("bounded single-pixel fixture did not finish"); +} + +#[test] +fn nonselected_fixed_primary_matches_analytic_color_and_legacy_r_with_less_work() { + for samples in [1, 4, 16, 64] { + for shadows in [false, true] { + let (fast, work, primaries) = render(task(samples, false, false, shadows), false); + let (legacy, legacy_work, legacy_primaries) = render(task(samples, false, false, shadows), true); + assert_eq!(fast, legacy, "same radiance without repeated identical primary samples"); + assert_eq!(primaries, 1); + assert_eq!(legacy_primaries, usize::from(samples)); + if samples == 1 { + assert_eq!(work, legacy_work); + } else { + assert!(work < legacy_work); + } + if !shadows { + // White roughness-one conductor, constant RGB(1,.5,.25), fixed + // 2x2 solid-angle strata: two z=.5 contributions average to1/3. + let expected = [1.0 / 3.0, 1.0 / 6.0, 1.0 / 12.0].map(|v| encode8(v / (1.0 + v))); + let image = ::image::load_from_memory(&fast).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); + } + } + } +} + +#[test] +fn selected_rough_primary_retains_every_sample_including_null_attempts() { + for samples in [4, 16, 64] { + let (actual, work, primaries) = render(task(samples, true, false, false), false); + let (reference, reference_work, reference_primaries) = render(task(samples, true, false, false), true); + assert_eq!(actual, reference); + assert_eq!(work, reference_work); + assert_eq!(primaries, usize::from(samples)); + assert_eq!(primaries, reference_primaries); + } +} + +#[test] +fn captured_face_override_is_resolved_before_nonselected_fast_path_finishes() { + let (png, work, count) = render(task(64, false, true, false), false); + let (reference, reference_work, reference_count) = render(task(64, false, true, false), true); + assert_eq!(png, reference); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [0, 0, 0, 255]); + assert!(work < reference_work); + assert_eq!(count, 1); + assert_eq!(reference_count, 64); +} + +#[test] +fn nonselected_visibility_keeps_shared_cancel_and_work_limit_refusal() { + for cancel_now in [false, true] { + let mut task = task(64, false, false, true); + for _ in 0..10000 { + 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())); + if cancel_now { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step(1).err().unwrap().code, if cancel_now { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + } +} + +#[test] +fn selected_sampling_cancellation_does_not_turn_partial_samples_into_png() { + let mut task = task(64, true, false, false); + for _ in 0..10000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.sample >= 1 { + break; + } + } + assert!(task.sample >= 1 && task.sample < 64); + task.cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert!(!task.done); +} + +#[test] +fn reused_shading_preserves_original_per_add_radiance_bound() { + let mut task = task(64, false, false, false); + for _ in 0..10000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.repeatable_primary) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.repeatable_primary)); + let error = task.finish_sample(Vec3::new(1e12 / 32.0, 0.0, 0.0)).unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert_eq!(task.sample, 32); + assert!(!task.done); + assert!(task.pixels.is_empty()); +} + +#[test] +fn request_admission_and_task_slot_caps_are_not_expanded() { + let fast = task(64, false, false, false); + let legacy = task(64, false, false, false); + assert_eq!(*fast.visibility_owner.options(), *legacy.visibility_owner.options()); + assert_eq!(fast.admission.estimated_total_bytes, legacy.admission.estimated_total_bytes); + assert_eq!(fast.visibility_owner.options().reflections.as_ref().unwrap().samples, 64); + assert!(std::mem::size_of::() <= 4096); + assert_eq!(crate::raytrace::MAX_WORK, 1_000_000_000); + assert_eq!(job::image::MAX_JOB_BYTES, 384 * 1024 * 1024); +} + +// Fixed spatial-generator reuse regressions. Source written; execution pending. + +fn spatial_reuse_fixture(s: u8, r: u8, selected: bool, face_override: bool, shadows: bool) -> ImageTask { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + primary_samples: s, + lights: Some(Vec::new()), + shadows, + reflections: Some(ReflectionOptions { + bodies: vec![ReflectionBody { body: if selected { "Visible" } else { "Hidden" }.into(), mode: ReflectionMode::RoughSpecular }], + max_bounces: 2, + samples: r, + }), + ..Default::default() + }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + 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(options.clone()), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + }; + let mut scene = scene(face_override); + // Explicit full coverage fixture; hidden selected body remains far off-axis. + let visible = Arc::get_mut(&mut scene.meshes[0].mesh).unwrap(); + for p in &mut visible.positions { + p.x *= 5.0; + p.y *= 5.0; + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + ImageTask::new_with_environment(scene, request, CancelToken::default(), options, Some(environment())).unwrap() +} + +type SpatialBoundary = (u8, u8, u16, [u64; 6]); +fn spatial_reference_render(mut task: ImageTask, revoke: bool) -> (Vec, Vec) { + let mut boundaries = Vec::new(); + for _ in 0..1_000_000 { + // Exactly the established reference technique. Revoke before every step, + // including BEFORE the first completed shade could retain a cache entry. + if revoke && let Some(p) = task.pending.as_mut() { + p.repeatable_primary = false; + } + let before = task.work.used(); + let previous = (task.pixel, task.spatial, task.sample); + let poll = task.step(1).unwrap(); + assert!(task.work.used() - before <= 4); + if revoke { + assert!( + task.pending.as_ref().is_none_or(|p| p.light <= task.lights.lights().len()), + "revoked-proof reference retained a completed cache entry" + ); + } + if (task.pixel, task.spatial) == (previous.0, previous.1) && task.sample > previous.2 { + let p = task.pixel_radiance; + let s = task.spatial_radiance; + boundaries.push(( + task.spatial, + task.sample, + task.primary_coverage, + [p.x.to_bits(), p.y.to_bits(), p.z.to_bits(), s.x.to_bits(), s.y.to_bits(), s.z.to_bits()], + )); + } + if let TaskPoll::Complete(png) = poll { + return (png, boundaries); + } + } + panic!("bounded actual-consumer spatial fixture did not finish"); +} + +#[test] +fn intra_spatial_nonselected_reuse_matches_uncached_ordered_sums_coverage_and_png() { + for s in [4, 16] { + for r in [1, 4, 16, 64] { + for shadows in [false, true] { + for face_override in [false, true] { + let fast = spatial_reference_render(spatial_reuse_fixture(s, r, false, face_override, shadows), false); + let reference = spatial_reference_render(spatial_reuse_fixture(s, r, false, face_override, shadows), true); + assert_eq!(fast, reference, "exact actual ImageTask PNG and per-S accumulator bits/coverage"); + assert_eq!(fast.1.len(), usize::from(s) * usize::from(r)); + for (ordinal, boundary) in fast.1.iter().enumerate() { + assert_eq!(boundary.0, (ordinal / usize::from(r)) as u8); + assert_eq!(boundary.1, (ordinal % usize::from(r)) as u8 + 1); + assert_eq!(boundary.2, ordinal as u16 + 1); + } + if !face_override { + assert!( + fast.1.iter().any(|b| b.3[..3].iter().any(|v| f64::from_bits(*v) > 0.0)), + "HDR actual-consumer comparison must include positive radiance" + ); + } + } + } + } + } +} + +#[test] +fn completed_spatial_reuse_checks_cancel_and_work_limit_before_any_mutation() { + for cancel in [false, true] { + for ordinal in [1, 2] { + let mut task = spatial_reuse_fixture(16, 64, false, false, true); + for _ in 0..1_000_000 { + if task.sample == ordinal + && task + .pending + .as_ref() + .is_some_and(|p| p.repeatable_primary && p.bounce == 0 && p.hit.is_some() && p.light == task.lights.lights().len() + 1) + { + break; + } + task.step(1).unwrap(); + } + assert_eq!(task.sample, ordinal); + assert!(task.pending.as_ref().is_some_and(|p| p.light == task.lights.lights().len() + 1)); + let before = (task.work.used(), task.sample, task.primary_coverage, task.pixel_radiance); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!((task.work.used(), task.sample, task.primary_coverage, task.pixel_radiance), before); + assert!(!task.done && task.pixels.is_empty()); + } + } +} +// Bits: directional, point, spot, rectangle, lowered LED, HDR. Every source can +// be isolated, preventing an all-black or one-source-only comparison from +// masquerading as combined-consumer coverage. Inputs are original fixtures. +fn spatial_lights_fixture(config: (u8, u8, u32, u32, bool), mask: u8, width: u32, partial: bool) -> ImageTask { + let (s, r, n, seed, shadows) = config; + let previous = spatial_reuse_fixture(s, r, false, false, shadows); + let (fixture_scene, mut options) = previous.visibility_owner.into_capture(); + options.exposure_ev = 1.0; + options.lights = Some(if mask & 1 != 0 { + vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }] + } else { + Vec::new() + }); + let point = job::PunctualLightOptions { + position_mm: [0.0, 0.0, 40.0], + color: [1.0, 0.5, 0.25], + intensity: 1.0, + reference_distance_mm: 40.0, + minimum_distance_mm: 0.001, + cone: None, + }; + let mut punctual = Vec::new(); + if mask & 2 != 0 { + punctual.push(point); + } + if mask & 4 != 0 { + punctual.push(job::PunctualLightOptions { + color: [0.25, 1.0, 0.5], + cone: Some(job::SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.7, outer_half_angle_radians: 1.4 }), + ..point + }); + } + options.punctual_lights = if punctual.is_empty() { None } else { Some(punctual) }; + if mask & 8 != 0 { + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [-5.0, 0.0, 50.0], + edge_u_mm: [20.0, 0.0, 0.0], + edge_v_mm: [0.0, -20.0, 0.0], + color: [0.5, 0.25, 1.0], + intensity: 3.0, + }]); + options.area_samples = Some(n); + } + if mask & 16 != 0 { + job::led_strip::LedStripOptions { + center_mm: [5.0, 0.0, 50.0], + length_mm: 20.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.25, 0.5], + intensity: 4.0, + } + .append_to(&mut options, n) + .unwrap(); + } + if options.area_lights.is_some() { + options.seed = Some(seed); + } + let mut scene = fixture_scene; + if partial { + let mesh = Arc::get_mut(&mut scene.meshes[0].mesh).unwrap(); + mesh.positions[0].x = 0.0; + mesh.positions[3].x = 0.0; + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + } + let request = ImageRequest { width, raytrace: Some(options.clone()), ..previous.request }; + ImageTask::new_with_environment(scene, request, previous.cancel, options, if mask & 32 != 0 { Some(environment()) } else { None }).unwrap() +} + +#[test] +fn spatial_reuse_actual_nonzero_light_consumers_and_seeded_union_match_reference() { + for mask in [1, 2, 4, 8, 16, 32, 63] { + let config = (4, 4, 4, 7, false); + let fast = spatial_reference_render(spatial_lights_fixture(config, mask, 1, false), false); + let reference = spatial_reference_render(spatial_lights_fixture(config, mask, 1, false), true); + assert_eq!(fast, reference, "actual isolated source mask {mask}"); + assert!(fast.1.iter().any(|b| b.3[..3].iter().any(|v| f64::from_bits(*v) > 0.0)), "source mask {mask} contributed no radiance"); + } + // Finite pairwise matrix, not a timing benchmark. R64 is covered by the HDR + // matrix above; every allowed rectangle N and two nonzero seeds are explicit. + for (s, r, n) in [(4, 4, 1), (16, 4, 4), (4, 16, 16), (4, 4, 64)] { + for seed in [7, 0xfedc_ba98] { + for shadows in [false, true] { + let config = (s, r, n, seed, shadows); + assert_eq!( + spatial_reference_render(spatial_lights_fixture(config, 63, 1, false), false), + spatial_reference_render(spatial_lights_fixture(config, 63, 1, false), true) + ); + } + } + } +} + +#[test] +fn mixed_pixels_spatial_hits_misses_and_independent_jobs_do_not_share_reuse() { + for s in [4, 16] { + for shadows in [false, true] { + let config = (s, 4, 4, 7, shadows); + let fast = spatial_reference_render(spatial_lights_fixture(config, 63, 3, true), false); + let reference = spatial_reference_render(spatial_lights_fixture(config, 63, 3, true), true); + assert_eq!(fast, reference); + assert_eq!(fast.1.len(), 3 * usize::from(s) * 4); + assert!(fast.1.iter().any(|b| b.2 == 0), "fixture must include primary misses"); + assert!(fast.1.iter().any(|b| b.2 > 0), "fixture must include primary hits"); + assert!(fast.1.iter().any(|b| b.0 == s - 1 && b.1 == 4 && b.2 == u16::from(s) * 2), "middle pixel must retain half spatial coverage"); + // A new captured job with different sources/seed/coverage has its own + // actual reference; prior jobs must not contribute state to it. + let changed = (s, 4, 16, 0xfedc_ba98, shadows); + assert_eq!( + spatial_reference_render(spatial_lights_fixture(changed, 16, 2, false), false), + spatial_reference_render(spatial_lights_fixture(changed, 16, 2, false), true) + ); + } + } +} + +fn at_first_completed_spatial_primary() -> ImageTask { + let mut task = spatial_reuse_fixture(4, 4, false, false, true); + for _ in 0..1_000_000 { + if task.sample == 1 && task.pending.as_ref().is_some_and(|p| p.light == task.lights.lights().len() + 1) { + return task; + } + task.step(1).unwrap(); + } + panic!("actual shading did not reach reusable completion"); +} + +#[test] +fn reused_r_addition_enforces_finite_bound_and_coverage_before_publication() { + for corrupt in [0, 1, 2, 3] { + let mut task = at_first_completed_spatial_primary(); + match corrupt { + 0 => { + task.pixel_radiance = Vec3::new(1e12, 0.0, 0.0); + task.pending.as_mut().unwrap().radiance = Vec3::new(1.0, 0.0, 0.0); + } + 1 => { + task.pending.as_mut().unwrap().radiance = Vec3::new(f64::NAN, 0.0, 0.0); + } + 2 => { + task.pending.as_mut().unwrap().radiance = Vec3::new(f64::INFINITY, 0.0, 0.0); + } + _ => { + task.primary_coverage = 1024; + } + } + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::InvalidScene); + assert!(!task.done && task.pixels.is_empty()); + } +} + +#[test] +fn completed_marker_refuses_malformed_proof_sample_bounce_hit_and_shading_state() { + for corrupt in 0..19 { + let mut task = at_first_completed_spatial_primary(); + match corrupt { + 0 => task.pending.as_mut().unwrap().repeatable_primary = false, + 1 => task.pending.as_mut().unwrap().bounce = 1, + 2 => task.pending.as_mut().unwrap().hit = None, + 3 => task.sample = 0, + 4 => task.sample = task.sample_count(), + 5 => task.pending.as_mut().unwrap().punctual_shadow = true, + 6 => task.pending.as_mut().unwrap().area_ready = true, + 7 => task.pending.as_mut().unwrap().environment_sample = 0, + 8 => task.pending.as_mut().unwrap().area_light = 1, + 9 => { + let (fixture_scene, mut fixture_options) = task.visibility_owner.into_capture(); + fixture_options.reflections.as_mut().unwrap().bodies[0].body = "Visible".into(); + task.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + } + 10 => task.sample = task.sample_count() + 1, + 11 => task.pending.as_mut().unwrap().light = task.lights.lights().len() + 2, + 12 => task.finish_spatial = true, + 13 => task.emit_spatial_pixel = true, + 14 => task.spatial = task.visibility_owner.options().primary_samples, + 15 => task.pending.as_mut().unwrap().emission_cursor = 1, + 16 => task.pending.as_mut().unwrap().surface_cursor = 1, + 17 => task.pending.as_mut().unwrap().surface_ready = false, + _ => task.pending.as_mut().unwrap().surface_index = Some(0), + } + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::InvalidScene); + assert!(!task.done && task.pixels.is_empty()); + } +} +#[test] +fn spatial_reuse_observes_cancellation_and_limit_at_shading_finalization_and_emission() { + for phase in 0..3 { + for cancel in [false, true] { + let mut task = spatial_reuse_fixture(4, 4, false, false, true); + let reached = |task: &ImageTask| match phase { + 0 => task.sample == 0 && task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.environment_sample == 0), + 1 => task.finish_spatial, + _ => task.emit_spatial_pixel, + }; + for _ in 0..200_000 { + if reached(&task) { + break; + } + task.step(1).unwrap(); + } + assert!(reached(&task)); + let before = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = before; + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert!(!task.done && task.pixels.is_empty()); + } + } +} + +fn spatial_quantum_png(mut task: ImageTask, quantum: usize) -> Vec { + for _ in 0..1_000_000 { + let used = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - used <= 4, "public work quantum exceeded"); + if let TaskPoll::Complete(png) = poll { + return png; + } + } + panic!("bounded spatial quantum fixture did not finish"); +} + +#[test] +fn spatial_reuse_quantum_partitions_preserve_complete_png_and_public_work_bound() { + for s in [4, 16] { + let fixture = || spatial_lights_fixture((s, 4, 4, 7, true), 63, 3, true); + let reference = spatial_reference_render(fixture(), true).0; + for quantum in [1, 4, 16384] { + assert_eq!(spatial_quantum_png(fixture(), quantum), reference); + } + } +} + +fn spatial_surface_fixture(s: u8, r: u8, selected: bool) -> ImageTask { + let previous = spatial_lights_fixture((s, r, 4, 7, true), 63, 2, true); + let (fixture_scene, mut options) = previous.visibility_owner.into_capture(); + options.surface_effects = Some(vec![crate::surface_patterns::SurfaceEffect { + body: "Visible".into(), + frame: Default::default(), + repeat_mm: [20.0, 27.0, 31.0], + roughness_amplitude: 0.2, + bump_amplitude_mm: 0.4, + }]); + if selected { + options.reflections.as_mut().unwrap().bodies[0].body = "Visible".into(); + } + let request = ImageRequest { raytrace: Some(options.clone()), ..previous.request }; + ImageTask::new_with_environment(fixture_scene, request, previous.cancel, options, Some(environment())).unwrap() +} + +#[test] +fn surface_shared_hit_preserves_aa_ordered_prefixes_coverage_and_completed_png() { + for s in [4, 16] { + for r in [1, 4, 16] { + for selected in [false, true] { + let expected = spatial_reference_render(spatial_surface_fixture(s, r, selected), true); + let actual = spatial_reference_render(spatial_surface_fixture(s, r, selected), false); + assert_eq!(actual, expected, "S={s}, R={r}, selected={selected}"); + for quantum in [4, 16384] { + assert_eq!(spatial_quantum_png(spatial_surface_fixture(s, r, selected), quantum), expected.0); + } + } + } + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/dielectric_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/dielectric_tests.rs new file mode 100644 index 000000000..8d7eaa93d --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/dielectric_tests.rs @@ -0,0 +1,1203 @@ +use super::*; +use crate::{ + ProductMesh, + job::{CancelToken, DielectricBoundary, ImageRequest, Integrator, RaytraceOptions, TaskPoll}, +}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +pub(in crate::raytrace) fn box_body(thickness: f64) -> ProductMesh { + let positions = (0..8) + .map(|i| Vec3::new(if i & 1 == 0 { -10.0 } else { 10.0 }, if i & 2 == 0 { -10.0 } else { 10.0 }, if i & 4 == 0 { 0.0 } else { thickness })) + .collect(); + let triangles = + vec![[0, 2, 3], [0, 3, 1], [4, 5, 7], [4, 7, 6], [0, 4, 6], [0, 6, 2], [1, 3, 7], [1, 7, 5], [0, 1, 5], [0, 5, 4], [2, 6, 7], [2, 7, 3]]; + ProductMesh { + transmission: None, + name: "captured slab@occurrence-2".into(), + mesh: Arc::new(Mesh { positions, triangles, ..Default::default() }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + } +} +pub(in crate::raytrace) fn scene(body: ProductMesh) -> ProductScene { + let bounds = body.mesh.bounds(); + ProductScene { meshes: vec![body], bounds } +} +pub(in crate::raytrace) fn input(boundary: DielectricBoundary) -> DielectricOptions { + DielectricOptions { + body_index: 0, + body_name: "captured slab@occurrence-2".into(), + boundary, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + } +} +fn environment() -> Option { + Some(crate::job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }) +} +pub(in crate::raytrace) fn request(options: RaytraceOptions) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(options), + camera, + width: 1, + height: 1, + background: [255; 3], + transparent_background: false, + } +} +fn render(scene: ProductScene, options: RaytraceOptions) -> [u8; 4] { + let request = request(options.clone()); + let mut task = super::super::image::ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + return image.get_pixel(0, 0).0; + } + } + panic!("bounded dielectric fixture failed to finish"); +} + +#[test] +fn normal_interface_has_four_percent_reflection() { + let hit = interface(-Vec3::Z, Vec3::Z, 1.0, 1.5).unwrap(); + assert!((hit.reflectance - 0.04).abs() < 1e-14); + assert_eq!(hit.transmitted, Some(-Vec3::Z)); + assert_eq!(hit.reflected, Vec3::Z); +} + +#[test] +fn thirty_degree_snell_and_parallel_exit_are_reversible() { + let incident = Vec3::new(0.5, 0.0, -(3.0f64).sqrt() / 2.0); + let enter = interface(incident, Vec3::Z, 1.0, 1.5).unwrap(); + let inside = enter.transmitted.unwrap(); + assert!((inside.x - 1.0 / 3.0).abs() < 1e-14); + let exit = interface(inside, Vec3::Z, 1.5, 1.0).unwrap(); + assert!((exit.transmitted.unwrap() - incident).len() < 1e-14); + assert!((exit.reflectance - enter.reflectance).abs() < 1e-14); +} + +#[test] +fn internal_grazing_ray_is_totally_reflected() { + let hit = interface(Vec3::new(0.8, 0.0, -0.6), Vec3::Z, 1.5, 1.0).unwrap(); + assert_eq!(hit.transmitted, None); + assert_eq!(hit.reflectance, 1.0); +} + +#[test] +fn beer_lambert_uses_actual_millimetre_path() { + let a = attenuation([0.1, 0.2, 0.0], 2.0).unwrap(); + let b = attenuation([0.1, 0.2, 0.0], 8.0).unwrap(); + assert!((b.x - a.x.powi(4)).abs() < 1e-14); + assert!((b.y - a.y.powi(4)).abs() < 1e-14); + assert_eq!(b.z, 1.0); +} + +#[test] +fn hostile_optics_are_refused() { + for v in [f64::NAN, f64::INFINITY, -1.0] { + assert!(interface(-Vec3::Z, Vec3::Z, v, 1.5).is_err()); + assert!(attenuation([v, 0.0, 0.0], 1.0).is_err()); + assert!(attenuation([0.0; 3], v).is_err()); + } + assert!(interface(Vec3::Z, Vec3::Z, 1.0, 1.5).is_err()); + assert_eq!(interface(Vec3::X, Vec3::Z, 1.0, 1.0).unwrap().reflectance, 0.0); +} + +#[test] +fn closed_box_certification_requires_complete_outward_boundary() { + let original = box_body(2.0); + assert!(matches!(certify(&scene(original.clone()), &input(DielectricBoundary::ClosedBox)), Ok(Certificate::ClosedBox(_)))); + let mut body = original.clone(); + Arc::make_mut(&mut body.mesh).triangles.pop(); + assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); + let mut body = original.clone(); + Arc::make_mut(&mut body.mesh).triangles[0].swap(0, 1); + assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); + let mut body = original; + let mesh = Arc::make_mut(&mut body.mesh); + mesh.triangles[1] = mesh.triangles[0]; + assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); +} + +#[test] +fn captured_occurrence_identity_and_unsupported_boundary_are_refused() { + let scene = scene(box_body(2.0)); + let mut material = input(DielectricBoundary::ClosedBox); + material.body_name = "captured slab@occurrence-1".into(); + assert!(certify(&scene, &material).is_err()); + material = input(DielectricBoundary::ThinSheet); + assert!(certify(&scene, &material).is_err()); +} + +#[test] +fn actual_png_closed_volume_absorption_uses_two_and_eight_mm() { + for thickness in [2.0, 8.0] { + let mut material = input(DielectricBoundary::ClosedBox); + material.ior = 1.0; + material.absorption_per_mm = [0.1, 0.0, 0.0]; + let options = RaytraceOptions { + dielectrics: vec![material], + environment: environment(), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let actual = render(scene(box_body(thickness)), options); + let linear = Vec3::new((-0.1 * thickness).exp(), 1.0, 1.0); + let mapped = super::super::lighting::map_to_display(linear, 0.0).unwrap(); + let encode = |v: f64| ((if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) * 255.0).round() as u8; + assert_eq!(actual, [encode(mapped.x), encode(mapped.y), encode(mapped.z), 255]); + } +} + +#[test] +fn actual_png_clear_volume_includes_multiple_fresnel_branches() { + let options = RaytraceOptions { + dielectrics: vec![input(DielectricBoundary::ClosedBox)], + environment: environment(), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let actual = render(scene(box_body(2.0)), options); + // Constant unit environment, no absorption: all branches sum to almost one. + // Eight boundaries drop only a very small unresolved Fresnel tail. + assert_eq!(actual, [188, 188, 188, 255]); +} + +#[test] +fn overlapping_volumes_are_refused_before_pixel_work() { + let mut scene = scene(box_body(2.0)); + scene.meshes.push(box_body(2.0)); + let first = input(DielectricBoundary::ClosedBox); + let mut second = first.clone(); + second.body_index = 1; + let options = RaytraceOptions { dielectrics: vec![first, second], ..Default::default() }; + assert!(super::super::image::admit(&scene, &request(options.clone()), &options).is_err()); +} + +#[test] +fn cancelled_dielectric_job_cannot_publish_png() { + let options = RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox)], ..Default::default() }; + let cancel = CancelToken::default(); + let mut task = super::super::image::ImageTask::new(scene(box_body(2.0)), request(options.clone()), cancel.clone(), options).unwrap(); + task.step(1).unwrap(); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, crate::job::ErrorCode::Cancelled); +} + +#[test] +fn runtime_dielectric_inputs_are_bounded_and_default_off() { + assert!(RaytraceOptions::default().dielectrics.is_empty()); + let options = RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox); 9], ..Default::default() }; + assert!(options.validate().is_err()); + let mut material = input(DielectricBoundary::ClosedBox); + material.thickness_mm = 1.0; + let options = RaytraceOptions { dielectrics: vec![material], ..Default::default() }; + assert!(options.validate().is_err()); + let oversized = serde_json::json!({"dielectrics": vec![input(DielectricBoundary::ThinSheet);9]}); + assert!(serde_json::from_value::(oversized).is_err()); + assert!(serde_json::from_value::(serde_json::json!({"dielectrics":[{"body_index":0,"body_name":"x".repeat(1025),"boundary":"closed_box","ior":1.5,"absorption_per_mm":[0,0,0],"thickness_mm":0}]})).is_err()); +} + +#[test] +fn oblique_parallel_slab_offset_scales_with_actual_thickness() { + let direction = Vec3::new(0.5, 0.0, -(3.0f64).sqrt() / 2.0); + let inside = interface(direction, Vec3::Z, 1.0, 1.5).unwrap().transmitted.unwrap(); + let mut offsets = Vec::new(); + for thickness in [2.0, 8.0] { + let bottom = Triangle::new([Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(10.0, -10.0, 0.0)]).unwrap(); + let ray = super::super::Ray::new(Vec3::new(0.0, 0.0, thickness), inside, 0.0, 100.0).unwrap(); + let hit = bottom.intersect(&ray).unwrap(); + let exit = ray.at(hit.distance).unwrap(); + assert!((hit.distance - thickness / -inside.z).abs() < 1e-13); + let undeviated_x = thickness * direction.x / -direction.z; + offsets.push(undeviated_x - exit.x); + } + assert!((offsets[1] - 4.0 * offsets[0]).abs() < 1e-13); +} + +#[test] +fn thin_sheet_is_certified_separately_and_duplicate_faces_refuse() { + let mut body = box_body(2.0); + Arc::make_mut(&mut body.mesh).triangles = vec![[4, 5, 7], [4, 7, 6]]; + let mut material = input(DielectricBoundary::ThinSheet); + material.ior = 1.0; + material.thickness_mm = 8.0; + material.absorption_per_mm = [0.1, 0.0, 0.0]; + assert!(matches!(certify(&scene(body.clone()), &material), Ok(Certificate::ThinSheet))); + let options = + RaytraceOptions { dielectrics: vec![material], environment: environment(), lights: Some(Vec::new()), shadows: false, ..Default::default() }; + let actual = render(scene(body.clone()), options); + let closed = RaytraceOptions { + environment: environment(), + dielectrics: vec![DielectricOptions { ior: 1.0, absorption_per_mm: [0.1, 0.0, 0.0], ..input(DielectricBoundary::ClosedBox) }], + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + assert_eq!(actual, render(scene(box_body(8.0)), closed)); + let mesh = Arc::make_mut(&mut body.mesh); + mesh.triangles[1] = mesh.triangles[0]; + assert!(certify(&scene(body), &input(DielectricBoundary::ThinSheet)).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_dielectric_job_uses_existing_host_and_retained_png_lease() { + use crate::job::{CpuHost, JobId, Phase}; + let host = CpuHost::for_platform().unwrap(); + let options = RaytraceOptions { + dielectrics: vec![input(DielectricBoundary::ClosedBox)], + environment: environment(), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let scene = scene(box_body(2.0)); + let weak = Arc::downgrade(&scene.meshes[0].mesh); + let id = JobId { session: 1655, serial: 1, generation: 1 }; + let handle = host.submit(id, 1, scene, request(options)).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + assert!(::image::load_from_memory(frame.png()).is_ok()); + assert!(weak.upgrade().is_none()); + assert!(host.admitted_bytes() > 0); + drop(handle); + assert!(host.admitted_bytes() > 0); + drop(frame); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while host.admitted_bytes() != 0 { + assert!(std::time::Instant::now() < deadline, "worker did not release terminal request record"); + std::thread::yield_now(); + } +} + +#[test] +fn secondary_environment_is_explicit_and_primary_background_remains_display_srgb() { + let options = + RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox)], lights: Some(Vec::new()), shadows: false, ..Default::default() }; + assert_eq!(render(scene(box_body(2.0)), options.clone()), [0, 0, 0, 255]); + let mut request = request(options.clone()); + request.camera.target.x = 50.0; + request.background = [20, 30, 40]; + request.raytrace.as_mut().unwrap().exposure_ev = 4.0; + let options = request.raytrace.clone().unwrap(); + let mut task = super::super::image::ImageTask::new(scene(box_body(2.0)), request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [20, 30, 40, 255]); + return; + } + } + panic!("primary background fixture failed to finish"); +} + +#[test] +fn typed_runtime_roundtrip_preserves_default_empty_and_explicit_lists() { + for options in [ + RaytraceOptions::default(), + RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }, + RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox)], environment: environment(), ..Default::default() }, + ] { + let encoded = serde_json::to_value(&options).unwrap(); + let decoded: RaytraceOptions = serde_json::from_value(encoded).unwrap(); + assert_eq!(decoded, options); + assert!(decoded.validate().is_ok()); + } +} + +#[test] +fn actual_oblique_png_selects_the_snell_shifted_colour_target() { + fn target(name: &str, y0: f64, y1: f64, color: Vec3) -> ProductMesh { + ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, y0, -1.0), Vec3::new(20.0, y0, -1.0), Vec3::new(20.0, y1, -1.0), Vec3::new(-20.0, y1, -1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: Some(crate::surface::OpaqueSurface::new(color, 0.0, 1.0, 1.0).unwrap()), + faces: Vec::new(), + } + } + let mut scene = scene(box_body(8.0)); + scene.meshes.push(target("near blue stripe", -20.0, 4.0, Vec3::Z)); + scene.meshes.push(target("far red stripe", 4.0, 20.0, Vec3::X)); + for body in &scene.meshes { + scene.bounds = scene.bounds.union(&body.mesh.bounds()); + } + // Entry at (0,0,8), incidence30deg. Independent Snell values give + // y=8/sqrt(8)+1/sqrt(3)=3.4058 for glass and 9/sqrt(3)=5.1962 + // for index-matched air at target z=-1, on opposite sides of y=4. + let shifted_y = 8.0 / 8.0f64.sqrt() + 1.0 / 3.0f64.sqrt(); + let straight_y = 9.0 / 3.0f64.sqrt(); + assert!(shifted_y < 4.0 && straight_y > 4.0); + let mut results = Vec::new(); + for ior in [1.5, 1.0] { + let options = RaytraceOptions { + dielectrics: vec![DielectricOptions { ior, ..input(DielectricBoundary::ClosedBox) }], + lights: Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 4.0 }]), + shadows: false, + ..Default::default() + }; + let mut request = request(options.clone()); + request.camera.yaw = 0.0; + request.camera.pitch = std::f64::consts::PI / 3.0; + request.camera.target = Vec3::new(0.0, 0.0, 8.0); + let mut task = super::super::image::ImageTask::new(scene.clone(), request, CancelToken::default(), options).unwrap(); + let mut pixel = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + pixel = Some(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0); + break; + } + } + results.push(pixel.expect("oblique slab fixture must finish")); + } + let glass = results[0]; + let matched = results[1]; + assert!(u16::from(glass[2]) > u16::from(glass[0]) + 50, "glass ray missed the predicted blue stripe: {glass:?}"); + assert!(u16::from(matched[0]) > u16::from(matched[2]) + 50, "index-matched ray missed the predicted red stripe: {matched:?}"); +} + +#[test] +fn thin_sheet_brewster_sums_polarizations_before_averaging() { + // tan(theta_B) = 3/2, so single-interface Rs = 25/169 and Rp = 0. + // The lossless slab returns Rs/(1+Rs) after the unpolarized average. + let direction = Vec3::new(3.0, 0.0, -2.0) / 13.0f64.sqrt(); + let material = input(DielectricBoundary::ThinSheet); + let (_, polarized) = polarized_interface(direction, Vec3::Z, 1.0, 1.5).unwrap(); + assert!((polarized[0] - 25.0 / 169.0).abs() < 1e-14); + assert!(polarized[1].abs() < 1e-28); + let (optics, reflected, transmitted) = thin_sheet(direction, Vec3::Z, &material).unwrap(); + let expected_r = 25.0 / 194.0; + let expected_t = 169.0 / 194.0; + assert!((reflected - Vec3::new(expected_r, expected_r, expected_r)).len() < 1e-14); + assert!((transmitted - Vec3::new(expected_t, expected_t, expected_t)).len() < 1e-14); + assert!((optics.transmitted.unwrap() - direction).len() < 1e-14); + // The old average-before-series result differs by this exact rational. + assert!((50.0 / 363.0 - reflected.x - 625.0 / 70422.0).abs() < 1e-14); +} + +#[test] +fn thin_sheet_normal_incidence_keeps_the_lossless_slab_limit() { + let material = input(DielectricBoundary::ThinSheet); + let (_, reflected, transmitted) = thin_sheet(-Vec3::Z, Vec3::Z, &material).unwrap(); + // Rs = Rp = 1/25: the two-interface lossless slab has R = 1/13. + let r = 1.0 / 13.0; + let t = 12.0 / 13.0; + assert!((reflected - Vec3::new(r, r, r)).len() < 1e-14); + assert!((transmitted - Vec3::new(t, t, t)).len() < 1e-14); +} + +#[test] +fn thin_sheet_matched_indices_keep_beer_lambert_transmission() { + let material = DielectricOptions { + ior: 1.0, + thickness_mm: 2.0, + absorption_per_mm: [2.0f64.ln() / 2.0, 4.0f64.ln() / 2.0, 0.0], + ..input(DielectricBoundary::ThinSheet) + }; + let (optics, reflected, transmitted) = thin_sheet(-Vec3::Z, Vec3::Z, &material).unwrap(); + assert_eq!(reflected, Vec3::ZERO); + assert!((transmitted - Vec3::new(0.5, 0.25, 1.0)).len() < 1e-14); + assert_eq!(optics.transmitted, Some(-Vec3::Z)); +} + +#[test] +fn thin_sheet_zero_thickness_index_matched_grazing_is_transparent() { + // Equal indices remove the interface; zero thickness means exp(-sigma * 0) = 1. + for absorption_per_mm in [[0.0; 3], [100.0, 0.25, 1.0]] { + let material = DielectricOptions { ior: 1.0, absorption_per_mm, ..input(DielectricBoundary::ThinSheet) }; + let (optics, reflected, transmitted) = thin_sheet(Vec3::X, Vec3::Z, &material).unwrap(); + assert_eq!(optics.reflectance, 0.0); + assert_eq!(optics.transmitted, Some(Vec3::X)); + assert_eq!(reflected, Vec3::ZERO); + assert_eq!(transmitted, Vec3::new(1.0, 1.0, 1.0)); + } +} + +#[test] +fn thin_sheet_positive_thickness_index_matched_grazing_refuses_without_tir() { + let material = DielectricOptions { ior: 1.0, thickness_mm: 1.0, ..input(DielectricBoundary::ThinSheet) }; + let optics = interface(Vec3::X, Vec3::Z, 1.0, 1.0).unwrap(); + assert_eq!(optics.transmitted, Some(Vec3::X)); + assert_eq!(optics.reflectance, 0.0); + assert!(matches!(thin_sheet(Vec3::X, Vec3::Z, &material), Err(TraceError::InvalidInput("grazing sheet thickness is unsupported")))); +} + +#[test] +fn thin_sheet_zero_thickness_grazing_still_validates_absorption() { + for sigma in [f64::NAN, f64::INFINITY, -1.0, 101.0] { + let material = DielectricOptions { ior: 1.0, absorption_per_mm: [sigma, 0.0, 0.0], ..input(DielectricBoundary::ThinSheet) }; + assert!(matches!(thin_sheet(Vec3::X, Vec3::Z, &material), Err(TraceError::InvalidInput("dielectric absorption or distance")))); + } +} + +#[test] +fn thin_sheet_absorbing_brewster_keeps_separate_internal_returns() { + let direction = Vec3::new(3.0, 0.0, -2.0) / 13.0f64.sqrt(); + let material = DielectricOptions { + // cos(theta_t) = 3/sqrt(13), hence the one-pass distance is 1 mm. + thickness_mm: 3.0 / 13.0f64.sqrt(), + absorption_per_mm: [2.0f64.ln(), 2.0f64.ln(), 0.0], + ..input(DielectricBoundary::ThinSheet) + }; + let (_, reflected, transmitted) = thin_sheet(direction, Vec3::Z, &material).unwrap(); + // Independent rational series with Rs = 25/169, Rp = 0, a = 1/2. + let r = 6625.0 / 75746.0; + let t = 65521.0 / 151492.0; + assert!((reflected - Vec3::new(r, r, 25.0 / 194.0)).len() < 1e-14); + assert!((transmitted - Vec3::new(t, t, 169.0 / 194.0)).len() < 1e-14); + assert!(reflected.x + transmitted.x < 1.0); +} + +#[test] +fn actual_png_brewster_thin_sheet_matches_reflected_energy() { + let mut sheet = box_body(2.0); + Arc::make_mut(&mut sheet.mesh).triangles.retain(|t| *t == [4, 5, 7] || *t == [4, 7, 6]); + let mut scene = scene(sheet); + let absorber = ProductMesh { + transmission: None, + name: "unlit opaque transmission target".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, -1.0), Vec3::new(20.0, -20.0, -1.0), Vec3::new(20.0, 20.0, -1.0), Vec3::new(-20.0, 20.0, -1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }; + scene.bounds = scene.bounds.union(&absorber.mesh.bounds()); + scene.meshes.push(absorber); + let options = RaytraceOptions { + dielectrics: vec![input(DielectricBoundary::ThinSheet)], + environment: environment(), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = request(options.clone()); + request.camera.yaw = 0.0; + request.camera.pitch = (2.0f64 / 3.0).atan(); + request.camera.target = Vec3::new(0.0, 0.0, 2.0); + let (_, direction) = request.camera.ray(0.5, 0.5, 1.0, 1.0); + assert!((-direction.z - 2.0 / 13.0f64.sqrt()).abs() < 1e-14); + let mut task = super::super::image::ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut pixel = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + pixel = Some(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0); + break; + } + } + // Only the reflected branch sees the unit white environment. R = 25/194 + // maps through Reinhard to 25/219, then sRGB to 95. The old R = 50/363 + // maps to 98, so this also detects a consumer still using the old series. + assert_eq!(pixel.expect("Brewster sheet fixture must finish"), [95, 95, 95, 255]); +} + +#[test] +fn strict_box_parent_selection_is_order_independent_and_opt_in() { + let bounds = |lo: f64, hi: f64| Bounds::new(Vec3::new(lo, lo, lo), Vec3::new(hi, hi, hi)).unwrap(); + let mut certificates = [None; MAX_OVERRIDES]; + certificates[0] = Some(Certificate::ClosedBox(bounds(2.0, 3.0))); + certificates[1] = Some(Certificate::ClosedBox(bounds(0.0, 5.0))); + certificates[2] = Some(Certificate::ClosedBox(bounds(1.0, 4.0))); + assert!(parents(&certificates, false).is_err()); + assert_eq!(parents(&certificates, true).unwrap(), [Some(2), None, Some(1), None, None, None, None, None]); + certificates.swap(0, 1); + assert_eq!(parents(&certificates, true).unwrap(), [None, Some(2), Some(0), None, None, None, None, None]); +} + +#[test] +fn nesting_opt_in_still_refuses_touching_equal_and_partially_overlapping_boxes() { + let outer = Bounds::new(Vec3::ZERO, Vec3::new(4.0, 4.0, 4.0)).unwrap(); + for (lo, hi) in [ + (Vec3::new(0.0, 1.0, 1.0), Vec3::new(3.0, 3.0, 3.0)), + (Vec3::new(4.0, 1.0, 1.0), Vec3::new(5.0, 3.0, 3.0)), + (Vec3::new(4.0, 4.0, 1.0), Vec3::new(5.0, 5.0, 3.0)), + (Vec3::new(4.0, 4.0, 4.0), Vec3::new(5.0, 5.0, 5.0)), + (Vec3::ZERO, Vec3::new(4.0, 4.0, 4.0)), + (Vec3::new(3.0, 1.0, 1.0), Vec3::new(5.0, 3.0, 3.0)), + ] { + let mut certificates = [None; MAX_OVERRIDES]; + certificates[0] = Some(Certificate::ClosedBox(outer)); + certificates[1] = Some(Certificate::ClosedBox(Bounds::new(lo, hi).unwrap())); + assert!(parents(&certificates, true).is_err()); + } +} + +pub(in crate::raytrace) fn nested_fixture(reverse: bool) -> (ProductScene, RaytraceOptions) { + let mut outer = box_body(4.0); + outer.name = "Outer".into(); + let mut inner = box_body(2.0); + inner.name = "Inner".into(); + for p in &mut Arc::make_mut(&mut inner.mesh).positions { + *p = Vec3::new(p.x * 0.5, p.y * 0.5, p.z + 1.0); + } + let mut scene = scene(outer); + scene.meshes.push(inner); + if reverse { + scene.meshes.reverse(); + } + let dielectrics = scene + .meshes + .iter() + .enumerate() + .map(|(body_index, body)| DielectricOptions { + body_index, + body_name: body.name.clone(), + boundary: DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: if body.name == "Outer" { [0.1, 0.2, 0.0] } else { [0.3, 0.4, 0.0] }, + thickness_mm: 0.0, + }) + .collect(); + (scene, RaytraceOptions { dielectrics, environment: environment(), lights: Some(Vec::new()), shadows: false, ..Default::default() }) +} + +#[test] +fn actual_nested_png_uses_parent_only_outside_the_inner_interval() { + for reverse in [false, true] { + let (scene, options) = nested_fixture(reverse); + assert!(super::super::image::admit(&scene, &request(options.clone()), &options).is_err()); + let mut task = super::super::image::ImageTask::new_with_environment_and_nested( + scene, + request(options.clone()), + CancelToken::default(), + options, + None, + true, + ) + .unwrap(); + let mut completed = false; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + // Outer length2, inner length2; Beer radiance (exp(-.8), exp(-1.2), 1). + // Reinhard then IEC sRGB encoding gives these independently fixed bytes. + assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]); + completed = true; + break; + } + } + assert!(completed, "nested final image did not complete"); + } +} + +#[test] +fn progressive_optics_keep_the_nested_certificate_opt_in_and_interactive_intent() { + let (scene, mut options) = nested_fixture(false); + options.progressive = Some(Default::default()); + options.validate().unwrap(); + let request = request(options.clone()); + // A DTO succeeding never grants a nesting certificate to an ordinary job. + assert!(super::super::image::admit(&scene, &request, &options).is_err()); + assert!(super::super::image::admit_with_nested(&scene, &request, &options, true).is_ok()); + let interactive = crate::job::interactive::cpu_request(&request).unwrap(); + assert_eq!(interactive.raytrace.as_ref().unwrap().dielectrics, options.dielectrics); + assert!(super::super::image::admit(&scene, &interactive, interactive.raytrace.as_ref().unwrap()).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_host_forwards_only_the_existing_nested_media_exception() { + use crate::job::{CpuHost, ErrorCode, JobId, JobOptions, Phase}; + let host = CpuHost::for_platform().unwrap(); + let (scene, options) = nested_fixture(false); + let request = request(options); + let nested = JobOptions { nested_media: true, ..Default::default() }; + assert!(host.admit(&scene, &request, JobOptions::default()).is_err()); + assert!(host.admit(&scene, &request, nested).is_ok()); + for bad in [ + JobOptions { samples: 2, ..nested }, + JobOptions { max_depth: 2, ..nested }, + JobOptions { seed: 7, ..nested }, + JobOptions { exposure_ev: 1.0, ..nested }, + JobOptions { transmission_samples: 2, ..nested }, + JobOptions { denoise: true, ..nested }, + JobOptions { linear_exr: true, ..nested }, + ] { + assert_eq!(host.admit(&scene, &request, bad).unwrap_err().code, ErrorCode::InvalidRequest); + } + let mut raster = request.clone(); + raster.integrator = Integrator::Raster; + raster.raytrace = None; + assert!(host.admit(&scene, &raster, nested).is_err()); + let handle = host.submit_with_options(JobId { session: 6302, serial: 1, generation: 1 }, 1, scene, request, nested).unwrap(); + assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + assert_eq!(handle.status().unwrap().options.nested_media, true); + let frame = handle.frame().unwrap().unwrap(); + let image = ::image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]); +} + +fn face_fixture(axis: usize, positive: bool) -> (Bounds, [Vec3; 3], Vec3, Vec3) { + let point = |a: f64, u: f64, v: f64| match axis { + 0 => Vec3::new(a, u, v), + 1 => Vec3::new(v, a, u), + 2 => Vec3::new(u, v, a), + _ => panic!("test axis"), + }; + let bounds = Bounds::new(Vec3::new(1.0, 1.0, 1.0), Vec3::new(4.0, 4.0, 4.0)).unwrap(); + let plane = if positive { 4.0 } else { 1.0 }; + let mut vertices = [point(plane, 1.0, 1.0), point(plane, 4.0, 1.0), point(plane, 4.0, 4.0)]; + if !positive { + vertices.swap(1, 2); + } + let normal = match axis { + 0 => Vec3::X, + 1 => Vec3::Y, + 2 => Vec3::Z, + _ => panic!("test axis"), + } * if positive { 1.0 } else { -1.0 }; + (bounds, vertices, normal, point(plane, 2.5, 2.5)) +} + +#[test] +fn exact_face_excludes_own_zero_depth_and_retains_one_ulp_neighbour_on_every_axis_and_side() { + use super::super::Ray; + for axis in 0..3 { + for positive in [false, true] { + let (bounds, vertices, normal, position) = face_fixture(axis, positive); + for entering in [false, true] { + let direction = if entering { -normal } else { normal }; + let incoming = Ray::new(position - direction, direction, 0.0, 10.0).unwrap(); + let face = exact_box_face(bounds, vertices, normal, position, incoming).unwrap(); + assert_eq!(face.point, position, "face diagonal is valid interior"); + let optics = interface(direction, -direction, if entering { 1.0 } else { 1.5 }, if entering { 1.5 } else { 1.0 }).unwrap(); + let reflected = face.spawn(optics.reflected, true).unwrap(); + let transmitted = face.spawn(optics.transmitted.unwrap(), false).unwrap(); + let triangle = Triangle::new(vertices).unwrap(); + assert!(triangle.intersect(&reflected).is_none(), "own reflected face at t0 must be excluded"); + assert!(triangle.intersect(&transmitted).is_none(), "own transmitted face at t0 must be excluded"); + assert_eq!(reflected.origin(), face.point); + assert_eq!(transmitted.origin(), face.point); + assert_eq!(transmitted.interval()[0], 0.0_f64.next_up()); + let plane = super::super::component(position, axis); + let next = if super::super::component(direction, axis) > 0.0 { plane.next_up() } else { plane.next_down() }; + let neighbour = vertices.map(|v| match axis { + 0 => Vec3::new(next, v.y, v.z), + 1 => Vec3::new(v.x, next, v.z), + 2 => Vec3::new(v.x, v.y, next), + _ => panic!("test axis"), + }); + let hit = Triangle::new(neighbour).unwrap().intersect(&transmitted).expect("one-ULP positive face must remain ahead"); + assert_eq!(hit.distance, (next - plane).abs()); + } + } + } +} + +#[test] +fn exact_face_recovers_certified_plane_without_clamping_or_blessing_ties() { + use super::super::Ray; + let (bounds, vertices, normal, point) = face_fixture(2, false); + let incoming = Ray::new(point - Vec3::Z, Vec3::Z, 0.0, 10.0).unwrap(); + let rounded = Vec3::new(point.x, point.y, point.z.next_up()); + let face = exact_box_face(bounds, vertices, normal, rounded, incoming).unwrap(); + assert_eq!(face.point, point); + for bad in [Vec3::new(1.0, 2.5, 1.0), Vec3::new(1.0, 1.0, 1.0), Vec3::new(1.0_f64.next_down(), 2.5, 1.0), Vec3::new(f64::NAN, 2.5, 1.0)] { + assert!(exact_box_face(bounds, vertices, normal, bad, incoming).is_err()); + } + let tied = Ray::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0), 0.0, 10.0).unwrap(); + // Even if rounded tangential reconstruction claims interior, independently + // equal actual ray/face depths cannot inherit the BVH ordinal's blessing. + let uncertain = Vec3::new(1.0_f64.next_up(), 1.0_f64.next_up(), 1.0); + assert!(exact_box_face(bounds, vertices, normal, uncertain, tied).is_err()); + assert!(exact_box_face(bounds, vertices, -normal, point, incoming).is_err()); + let other_bounds = Bounds::new(Vec3::ZERO, Vec3::new(4.0, 4.0, 4.0)).unwrap(); + assert!(exact_box_face(other_bounds, vertices, normal, point, incoming).is_err()); + let tangent = Ray::new(point - Vec3::X, Vec3::X, 0.0, 10.0).unwrap(); + assert!(exact_box_face(bounds, vertices, normal, point, tangent).is_err()); + assert!(face.spawn(Vec3::X, true).is_err()); + assert!(face.spawn(-Vec3::Z, false).is_err()); + assert!(face.spawn(Vec3::Z, true).is_err()); +} + +fn direct_capture(bodies: Vec) -> ProductScene { + let mut bounds = bodies[0].mesh.bounds(); + for body in &bodies[1..] { + let next = body.mesh.bounds(); + bounds.min = bounds.min.min(next.min); + bounds.max = bounds.max.max(next.max); + } + ProductScene { meshes: bodies, bounds } +} + +fn direct_box(name: &str, offset: f64) -> ProductMesh { + let mut body = box_body(1.0); + body.name = name.into(); + for p in &mut Arc::make_mut(&mut body.mesh).positions { + p.z += offset; + } + body +} + +fn direct_sheet(name: &str, offset: f64) -> ProductMesh { + let mut body = direct_box(name, offset); + let mesh = Arc::make_mut(&mut body.mesh); + mesh.triangles.truncate(2); + mesh.positions.truncate(4); + body +} + +fn direct_material(body: usize, name: &str, boundary: DielectricBoundary) -> DielectricOptions { + DielectricOptions { + body_index: body, + body_name: name.into(), + boundary, + ior: 1.0, + absorption_per_mm: [2.0_f64.ln(), 4.0_f64.ln(), 0.0], + thickness_mm: if boundary == DielectricBoundary::ThinSheet { 1.0 } else { 0.0 }, + } +} + +fn direct_ray(max: f64) -> super::super::Ray { + super::super::Ray::new(Vec3::new(0.25, 0.125, -2.0), Vec3::Z, 0.0, max).unwrap() +} + +fn direct_complete(source: &ProductScene, options: &RaytraceOptions, ray: super::super::Ray) -> Vec3 { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + let mut visibility = DirectVisibility::new(source, options, ray, MAX_DIRECT_CROSSINGS, &mut work, &cancel).unwrap(); + for _ in 0..10_000 { + if let Some(rgb) = visibility.step(&mut work, &cancel).unwrap() { + assert!(visibility.step(&mut work, &cancel).is_err()); + return rgb; + } + } + panic!("bounded direct connection did not complete"); +} + +fn direct_rgb(actual: Vec3, expected: Vec3) { + for (a, b) in [actual.x, actual.y, actual.z].into_iter().zip([expected.x, expected.y, expected.z]) { + assert!((a - b).abs() <= 1e-13, "actual={actual:?}, expected={expected:?}"); + } +} + +#[test] +fn direct_box_beer_uses_original_endpoints_and_multiplies_disjoint_rgb() { + let source = direct_capture(vec![direct_box("one", 0.0), direct_box("two", 3.0)]); + let first = direct_material(0, "one", DielectricBoundary::ClosedBox); + let second = direct_material(1, "two", DielectricBoundary::ClosedBox); + let options = RaytraceOptions { dielectrics: vec![first, second], ..Default::default() }; + // sigma=(ln2,ln4,0), two one-mm slabs: exp(-2*sigma)=(1/4,1/16,1). + direct_rgb(direct_complete(&source, &options, direct_ray(10.0)), Vec3::new(0.25, 0.0625, 1.0)); + let one = direct_capture(vec![direct_box("one", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "one", DielectricBoundary::ClosedBox)], ..Default::default() }; + direct_rgb(direct_complete(&one, &options, direct_ray(10.0)), Vec3::new(0.5, 0.25, 1.0)); +} + +#[test] +fn direct_sheet_shared_diagonal_is_one_crossing_and_uses_virtual_beer_distance() { + let source = direct_capture(vec![direct_sheet("sheet", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "sheet", DielectricBoundary::ThinSheet)], ..Default::default() }; + let ray = super::super::Ray::new(Vec3::new(0.25, 0.25, -2.0), Vec3::Z, 0.0, 10.0).unwrap(); + direct_rgb(direct_complete(&source, &options, ray), Vec3::new(0.5, 0.25, 1.0)); +} + +#[test] +fn direct_exterior_box_fresnel_is_not_a_refracted_or_infinite_bounce_slab() { + let source = direct_capture(vec![direct_box("glass", 0.0)]); + let material = DielectricOptions { ior: 1.5, absorption_per_mm: [0.0; 3], ..direct_material(0, "glass", DielectricBoundary::ClosedBox) }; + let options = RaytraceOptions { dielectrics: vec![material], ..Default::default() }; + // Normal external R=1/25; this straight connection has (24/25)^2, with no reflected returns. + direct_rgb(direct_complete(&source, &options, direct_ray(10.0)), Vec3::new(576.0 / 625.0, 576.0 / 625.0, 576.0 / 625.0)); + let sheet = direct_capture(vec![direct_sheet("sheet", 0.0)]); + let material = DielectricOptions { ior: 1.5, absorption_per_mm: [0.0; 3], ..direct_material(0, "sheet", DielectricBoundary::ThinSheet) }; + let options = RaytraceOptions { dielectrics: vec![material], ..Default::default() }; + // Existing incoherent sheet closure sums its virtual internal returns: (1-R)/(1+R)=12/13. + direct_rgb(direct_complete(&sheet, &options, direct_ray(10.0)), Vec3::new(12.0 / 13.0, 12.0 / 13.0, 12.0 / 13.0)); +} + +#[test] +fn direct_connection_keeps_unselected_opaque_blockers_and_half_open_light_endpoint() { + let options = RaytraceOptions::default(); + for (z, expected) in [(7.0, Vec3::ZERO), (8.0, Vec3::new(1.0, 1.0, 1.0)), (9.0, Vec3::new(1.0, 1.0, 1.0))] { + let source = direct_capture(vec![direct_sheet("opaque", z)]); + direct_rgb(direct_complete(&source, &options, direct_ray(10.0)), expected); + } + let source = direct_capture(vec![direct_box("glass", 0.0), direct_sheet("blocker", 5.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "glass", DielectricBoundary::ClosedBox)], ..Default::default() }; + assert_eq!(direct_complete(&source, &options, direct_ray(10.0)), Vec3::ZERO); +} + +#[test] +fn direct_connection_refuses_coincident_different_bodies_instead_of_skipping_opaque() { + let source = direct_capture(vec![direct_sheet("selected", 0.0), direct_sheet("opaque", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "selected", DielectricBoundary::ThinSheet)], ..Default::default() }; + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + let mut cursor = DirectVisibility::new(&source, &options, direct_ray(10.0), MAX_DIRECT_CROSSINGS, &mut work, &cancel).unwrap(); + for _ in 0..100 { + match cursor.step(&mut work, &cancel) { + Ok(None) => {} + Err(super::super::TraceError::InvalidInput(_)) => { + assert!(cursor.step(&mut work, &cancel).is_err()); + return; + } + other => panic!("ambiguous visibility must refuse: {other:?}"), + } + } + panic!("coincident boundary did not refuse"); +} + +#[test] +fn direct_connection_bounds_validate_identity_endpoints_overlap_and_crossing_budget() { + let source = direct_capture(vec![direct_box("glass", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "glass", DielectricBoundary::ClosedBox)], ..Default::default() }; + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + for limit in [0, MAX_DIRECT_CROSSINGS + 1] { + assert!(DirectVisibility::new(&source, &options, direct_ray(10.0), limit, &mut work, &cancel).is_err()); + } + // End at entry face, inside, and at exit face: all explicitly outside this foundation's domain. + for max in [2.0, 2.5, 3.0] { + assert!(DirectVisibility::new(&source, &options, direct_ray(max), 2, &mut work, &cancel).is_err()); + } + let inside = super::super::Ray::new(Vec3::new(0.25, 0.125, 0.5), Vec3::Z, 0.0, 10.0).unwrap(); + assert!(DirectVisibility::new(&source, &options, inside, 2, &mut work, &cancel).is_err()); + let mut wrong = options.clone(); + wrong.dielectrics[0].body_name = "wrong".into(); + assert!(DirectVisibility::new(&source, &wrong, direct_ray(10.0), 2, &mut work, &cancel).is_err()); + let overlap = direct_capture(vec![direct_box("a", 0.0), direct_box("b", 0.5)]); + let overlapping = RaytraceOptions { + dielectrics: vec![direct_material(0, "a", DielectricBoundary::ClosedBox), direct_material(1, "b", DielectricBoundary::ClosedBox)], + ..Default::default() + }; + assert!(DirectVisibility::new(&overlap, &overlapping, direct_ray(10.0), 4, &mut work, &cancel).is_err()); + let mut cursor = DirectVisibility::new(&source, &options, direct_ray(10.0), 1, &mut work, &cancel).unwrap(); + for _ in 0..100 { + match cursor.step(&mut work, &cancel) { + Ok(None) => {} + Err(super::super::TraceError::WorkLimit) => { + assert!(cursor.step(&mut work, &cancel).is_err()); + return; + } + other => panic!("insufficient crossing budget must refuse: {other:?}"), + } + } + panic!("crossing cap did not stop"); +} + +#[test] +fn direct_connection_spends_caller_work_and_cancellation_is_terminal_without_result() { + let source = direct_capture(vec![direct_box("glass", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "glass", DielectricBoundary::ClosedBox)], ..Default::default() }; + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + let mut cursor = DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + let used = work.used(); + assert!(used > 0); + assert_eq!(cursor.step(&mut work, &cancel).unwrap(), None); + assert_eq!(work.used(), used + 1); + work.charge(work.remaining(), &cancel).unwrap(); + assert!(matches!(cursor.step(&mut work, &cancel), Err(super::super::TraceError::WorkLimit))); + assert!(cursor.step(&mut work, &cancel).is_err()); + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + let mut cursor = DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + let used = work.used(); + cancel.cancel(); + assert!(matches!(cursor.step(&mut work, &cancel), Err(super::super::TraceError::Cancelled))); + assert_eq!(work.used(), used); + assert!(cursor.step(&mut work, &cancel).is_err()); + assert!(matches!(DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut work, &cancel), Err(super::super::TraceError::Cancelled))); +} + +#[test] +fn direct_connection_rejects_hostile_optics_before_any_dark_result() { + let source = direct_capture(vec![direct_box("glass", 0.0)]); + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(10000).unwrap(); + for value in [f64::NAN, f64::INFINITY, -1.0, 101.0] { + let material = DielectricOptions { absorption_per_mm: [value, 0.0, 0.0], ..direct_material(0, "glass", DielectricBoundary::ClosedBox) }; + let options = RaytraceOptions { dielectrics: vec![material], ..Default::default() }; + assert!(DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut work, &cancel).is_err()); + } + let material = DielectricOptions { ior: f64::NAN, ..direct_material(0, "glass", DielectricBoundary::ClosedBox) }; + let options = RaytraceOptions { dielectrics: vec![material], ..Default::default() }; + assert!(DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut work, &cancel).is_err()); +} + +#[test] +fn direct_connection_accepts_all_eight_disjoint_boxes_and_preserves_reverse_rgb() { + let bodies = (0..8).map(|i| direct_box(&format!("slab{i}"), f64::from(i) * 2.0)).collect(); + let source = direct_capture(bodies); + let dielectrics = (0..8).map(|i| direct_material(i, &format!("slab{i}"), DielectricBoundary::ClosedBox)).collect(); + let options = RaytraceOptions { dielectrics, ..Default::default() }; + let expected = Vec3::new(1.0 / 256.0, 1.0 / 65536.0, 1.0); + direct_rgb(direct_complete(&source, &options, direct_ray(20.0)), expected); + let reverse = super::super::Ray::new(Vec3::new(0.25, 0.125, 18.0), -Vec3::Z, 0.0, 20.0).unwrap(); + direct_rgb(direct_complete(&source, &options, reverse), expected); + let mut too_many = options.clone(); + too_many.dielectrics.push(direct_material(8, "ninth", DielectricBoundary::ClosedBox)); + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + assert!(DirectVisibility::new(&source, &too_many, direct_ray(20.0), 16, &mut work, &cancel).is_err()); +} + +#[test] +fn direct_connection_box_edge_is_refused_without_a_successful_fallback() { + let source = direct_capture(vec![direct_box("glass", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "glass", DielectricBoundary::ClosedBox)], ..Default::default() }; + let ray = super::super::Ray::new(Vec3::new(-10.0, -10.0, -2.0), Vec3::Z, 0.0, 10.0).unwrap(); + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + let mut cursor = DirectVisibility::new(&source, &options, ray, 2, &mut work, &cancel).unwrap(); + for _ in 0..100 { + match cursor.step(&mut work, &cancel) { + Ok(None) => {} + Err(super::super::TraceError::InvalidInput(_)) => return, + other => panic!("box edge must refuse: {other:?}"), + } + } + panic!("edge ambiguity did not stop"); +} + +#[test] +fn direct_connection_setup_certification_cannot_escape_caller_work_limit() { + let source = direct_capture(vec![direct_box("glass", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "glass", DielectricBoundary::ClosedBox)], ..Default::default() }; + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1).unwrap(); + assert!(matches!(DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut work, &cancel), Err(super::super::TraceError::WorkLimit))); + assert_eq!(work.used(), 1); +} + +#[test] +fn direct_oblique_sheet_is_one_certified_plane_with_original_beer_angle() { + let mut body = direct_sheet("oblique", 0.0); + for p in &mut Arc::make_mut(&mut body.mesh).positions { + p.z += 0.5 * p.x; + } + let source = direct_capture(vec![body]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "oblique", DielectricBoundary::ThinSheet)], ..Default::default() }; + let ray = super::super::Ray::new(Vec3::new(0.25, 0.25, -2.0), Vec3::Z, 0.0, 10.0).unwrap(); + // Plane z=x/2, index matched: thickness/cos(theta)=sqrt(5)/2 mm. + let distance = 5.0_f64.sqrt() / 2.0; + direct_rgb(direct_complete(&source, &options, ray), Vec3::new(2.0_f64.powf(-distance), 4.0_f64.powf(-distance), 1.0)); +} + +// Original owner regression cases, written before the private owner implementation. +fn direct_owner_fixture() -> DirectVisibilityOwner { + DirectVisibilityOwner::new( + direct_capture(vec![direct_box("owned glass", 0.0)]), + RaytraceOptions { dielectrics: vec![direct_material(0, "owned glass", DielectricBoundary::ClosedBox)], ..Default::default() }, + ) +} + +fn direct_owner_move(owner: DirectVisibilityOwner) -> DirectVisibilityOwner { + owner +} + +#[test] +fn direct_owner_move_each_poll_matches_borrowed_result_and_cumulative_work() { + let source = direct_capture(vec![direct_box("owned glass", 0.0)]); + let options = RaytraceOptions { dielectrics: vec![direct_material(0, "owned glass", DielectricBoundary::ClosedBox)], ..Default::default() }; + let cancel = CancelToken::default(); + let mut reference_work = super::super::WorkBudget::new(100_000).unwrap(); + let mut owner_work = super::super::WorkBudget::new(100_000).unwrap(); + let mut reference = DirectVisibility::new(&source, &options, direct_ray(10.0), 2, &mut reference_work, &cancel).unwrap(); + let mut owner = direct_owner_fixture(); + owner.begin(direct_ray(10.0), 2, &mut owner_work, &cancel).unwrap(); + assert_eq!(owner_work.used(), reference_work.used()); + for _ in 0..10_000 { + owner = direct_owner_move(owner); + let expected = reference.step(&mut reference_work, &cancel).unwrap(); + let actual = owner.step(&mut owner_work, &cancel).unwrap(); + assert_eq!(actual, expected); + assert_eq!(owner_work.used(), reference_work.used()); + assert_eq!(owner_work.remaining(), reference_work.remaining()); + if let Some(rgb) = actual { + direct_rgb(rgb, Vec3::new(0.5, 0.25, 1.0)); + assert_eq!(owner.source().meshes[0].name, "owned glass"); + assert_eq!(owner.options().dielectrics[0].body_name, "owned glass"); + return; + } + } + panic!("owner connection did not complete within the original fixture bound"); +} + +#[test] +fn direct_owner_rejects_active_begin_without_replacing_cursor_or_spending_work() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + let mut owner = direct_owner_fixture(); + owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + assert_eq!(owner.step(&mut work, &cancel).unwrap(), None); + let used = work.used(); + // This shorter replacement ray would end before the glass if accepted. + assert!(owner.begin(direct_ray(1.0), 2, &mut work, &cancel).is_err()); + assert_eq!(work.used(), used); + for _ in 0..10_000 { + if let Some(rgb) = owner.step(&mut work, &cancel).unwrap() { + direct_rgb(rgb, Vec3::new(0.5, 0.25, 1.0)); + return; + } + } + panic!("rejected begin lost the active connection"); +} + +#[test] +fn direct_owner_success_is_terminal_until_explicit_begin_on_the_same_capture() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + let mut owner = direct_owner_fixture(); + let mut first_cost = 0; + for connection in 0..2 { + owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + let mut complete = false; + for _ in 0..10_000 { + if let Some(rgb) = owner.step(&mut work, &cancel).unwrap() { + direct_rgb(rgb, Vec3::new(0.5, 0.25, 1.0)); + complete = true; + break; + } + } + assert!(complete); + let used = work.used(); + owner = direct_owner_move(owner); + assert!(matches!(owner.step(&mut work, &cancel), Err(super::super::TraceError::InvalidInput(_)))); + assert_eq!(work.used(), used); + if connection == 0 { + first_cost = used; + assert!(first_cost > 0); + } else { + assert_eq!(used, first_cost * 2); + } + } +} + +#[test] +fn direct_owner_cancelled_connection_stays_terminal_after_move_and_fresh_token() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + let mut owner = direct_owner_fixture(); + owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + assert_eq!(owner.step(&mut work, &cancel).unwrap(), None); + let used = work.used(); + cancel.cancel(); + assert!(matches!(owner.step(&mut work, &cancel), Err(super::super::TraceError::Cancelled))); + assert_eq!(work.used(), used); + owner = direct_owner_move(owner); + let fresh_token = CancelToken::default(); + assert!(matches!(owner.step(&mut work, &fresh_token), Err(super::super::TraceError::InvalidInput(_)))); + assert_eq!(work.used(), used); + assert!(matches!(owner.begin(direct_ray(10.0), 2, &mut work, &cancel), Err(super::super::TraceError::Cancelled))); + assert_eq!(work.used(), used); + assert!(owner.step(&mut work, &fresh_token).is_err()); + assert_eq!(work.used(), used); +} + +#[test] +fn direct_owner_exhausted_connection_stays_terminal_without_ledger_reset() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + let mut owner = direct_owner_fixture(); + owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + assert_eq!(owner.step(&mut work, &cancel).unwrap(), None); + work.charge(work.remaining(), &cancel).unwrap(); + let used = work.used(); + assert!(matches!(owner.step(&mut work, &cancel), Err(super::super::TraceError::WorkLimit))); + owner = direct_owner_move(owner); + assert!(matches!(owner.step(&mut work, &cancel), Err(super::super::TraceError::InvalidInput(_)))); + assert_eq!(work.used(), used); + assert_eq!(work.remaining(), 0); + assert!(matches!(owner.begin(direct_ray(10.0), 2, &mut work, &cancel), Err(super::super::TraceError::WorkLimit))); + assert_eq!(work.used(), used); + assert!(owner.step(&mut work, &cancel).is_err()); + assert_eq!(work.used(), used); +} + +#[test] +fn direct_owner_idle_and_failed_begin_do_not_create_a_connection() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(1000).unwrap(); + let mut owner = direct_owner_fixture(); + assert!(owner.step(&mut work, &cancel).is_err()); + assert_eq!(work.used(), 0); + assert!(owner.begin(direct_ray(10.0), 0, &mut work, &cancel).is_err()); + let used = work.used(); + assert_eq!(used, 1); // The original constructor charges before checking the limit. + owner = direct_owner_move(owner); + assert!(owner.step(&mut work, &cancel).is_err()); + assert_eq!(work.used(), used); + owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + assert_eq!(owner.step(&mut work, &cancel).unwrap(), None); +} + +#[test] +fn direct_owner_crossing_limit_error_stays_terminal_after_move() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + let mut owner = direct_owner_fixture(); + owner.begin(direct_ray(10.0), 1, &mut work, &cancel).unwrap(); + let mut refused = false; + for _ in 0..10_000 { + match owner.step(&mut work, &cancel) { + Ok(None) => {} + Err(super::super::TraceError::WorkLimit) => { + refused = true; + break; + } + other => panic!("crossing-limited owner returned {other:?}"), + } + } + assert!(refused); + let used = work.used(); + owner = direct_owner_move(owner); + assert!(matches!(owner.step(&mut work, &cancel), Err(super::super::TraceError::InvalidInput(_)))); + assert_eq!(work.used(), used); +} + +#[test] +fn direct_owner_consuming_capture_discards_active_cursor_before_a_new_context() { + let cancel = CancelToken::default(); + let mut work = super::super::WorkBudget::new(100_000).unwrap(); + let mut owner = direct_owner_fixture(); + owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + assert_eq!(owner.step(&mut work, &cancel).unwrap(), None); + let used = work.used(); + let (mut source, mut options) = owner.into_capture(); + source.meshes[0].name = "new capture".into(); + options.dielectrics[0].body_name = "new capture".into(); + options.dielectrics[0].absorption_per_mm = [0.0; 3]; + let mut new_owner = DirectVisibilityOwner::new(source, options); + assert!(new_owner.step(&mut work, &cancel).is_err()); + assert_eq!(work.used(), used); + new_owner.begin(direct_ray(10.0), 2, &mut work, &cancel).unwrap(); + assert!(work.used() > used); + for _ in 0..10_000 { + if let Some(rgb) = new_owner.step(&mut work, &cancel).unwrap() { + assert_eq!(rgb, Vec3::new(1.0, 1.0, 1.0)); + return; + } + } + panic!("new owner did not complete its new capture"); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/environment_image_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/environment_image_tests.rs new file mode 100644 index 000000000..5338ff52b --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/environment_image_tests.rs @@ -0,0 +1,310 @@ +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 { + cpu_progressive_every_pass: true, + 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) -> Vec { + 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::() / 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)>, + png: Vec, + work: u64, +} + +fn progressive_hdr_png(samples_per_pixel: u32, seed: u32, quantum: usize, environment: Option) -> 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::>(), 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()); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/environment_reflection_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/environment_reflection_tests.rs new file mode 100644 index 000000000..9060f777a --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/environment_reflection_tests.rs @@ -0,0 +1,300 @@ +use super::*; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::lighting::{HdrSource, environment_input::EnvironmentInput}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn environment(bright: bool, rotation: f64) -> 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 i in 0..8 { + bytes.extend_from_slice(&if bright { if i == 0 { [128, 64, 16, 133] } else { [0; 4] } } else { [128, 64, 32, 129] }); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), rotation, 1.0, 64).unwrap() +} +fn scene(normal: Vec3) -> ProductScene { + let normal = normal / normal.len(); + let u = normal.cross(Vec3::X); + let u = u / u.len() * 10.0; + let v = normal.cross(u); + let mesh = Arc::new(Mesh { + positions: vec![-u - v, u - v, u + v, -u + v], + normals: vec![normal; 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: "Metal".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(mode: ReflectionMode) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { + cpu_progressive_every_pass: true, + 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()), + reflections: Some(ReflectionOptions { bodies: vec![ReflectionBody { body: "Metal".into(), mode }], max_bounces: 1, samples: 64 }), + ..Default::default() + }), + camera, + width: 9, + height: 9, + background: [13, 27, 41], + transparent_background: false, + } +} +fn render(scene: ProductScene, request: ImageRequest, input: Option) -> Vec { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new_with_environment(scene, request, CancelToken::default(), options, input).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("bounded environment reflection did not finish"); +} +fn centre(bytes: &[u8]) -> [u8; 4] { + ::image::load_from_memory(bytes).unwrap().to_rgba8().get_pixel(4, 4).0 +} +fn expected(radiance: [f64; 3]) -> [u8; 4] { + let c = radiance.map(|v| encode8(v / (1.0 + v))); + [c[0], c[1], c[2], 255] +} + +#[test] +fn ideal_metal_mirror_receives_environment_once_and_camera_background_stays_independent() { + let req = request(ReflectionMode::Mirror); + assert_eq!(centre(&render(scene(Vec3::Z), req.clone(), None)), [0, 0, 0, 255]); + assert_eq!(centre(&render(scene(Vec3::Z), req.clone(), Some(environment(false, 0.0)))), expected([1.0, 0.5, 0.25])); + let mut empty = req; + empty.raytrace.as_mut().unwrap().reflections = Some(ReflectionOptions::default()); + let image = ::image::load_from_memory(&render( + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + empty, + Some(environment(false, 0.0)), + )) + .unwrap() + .to_rgba8(); + assert!(image.pixels().all(|p| p.0 == [13, 27, 41, 255])); +} + +#[test] +fn rough_metal_environment_matches_independent_sample_weights_without_extra_nee() { + let mut factor = 0.0; + // Normal-view white conductor at roughness1: null for z<=0, weight=2z/(1+z). + // Only the deterministic variate key is shared; no BRDF/PDF implementation is reused. + for sample in 0..64 { + let u = reflection::variates(40, sample, 0, 64).unwrap(); + let z = 1.0 - 2.0 * u[0]; + if z > 0.0 { + factor += 2.0 * z / (1.0 + z) / 64.0; + } + } + let req = request(ReflectionMode::RoughSpecular); + let png = render(scene(Vec3::Z), req.clone(), Some(environment(false, 0.0))); + assert_eq!(centre(&png), expected([factor, factor * 0.5, factor * 0.25])); + assert_eq!(png, render(scene(Vec3::Z), req, Some(environment(false, 0.0)))); +} + +#[test] +fn combined_hdr_equal_anisotropy_point_and_led_match_independent_radiance_sum() { + let mut req = anisotropic_request(ReflectionMode::RoughSpecular, true); + let options = req.raytrace.as_mut().unwrap(); + options.punctual_lights = Some(vec![job::PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0, 0.5, 0.25], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + job::led_strip::LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + } + .append_to(options, 1) + .unwrap(); + let mut reflected = 0.0; + for sample in 0..64 { + let u = reflection::variates(40, sample, 0, 64).unwrap(); + let z = 1.0 - 2.0 * u[0]; + if z > 0.0 { + reflected += 2.0 * z / (1.0 + z) / 64.0; + } + } + // Normal-view white conductor, roughness1: f*cos=1/(4*pi). + // Point at its reference distance contributes Li=1; LED contributes Le*A/r²=.08. + // Selected reflection receives HDR through BSDF misses only, never a second NEE term. + let total = reflected + 1.08 / (4.0 * std::f64::consts::PI); + let combined = render(scene(Vec3::Z), req.clone(), Some(environment(false, 0.0))); + assert_eq!(centre(&combined), expected([total, total * 0.5, total * 0.25])); + req.raytrace.as_mut().unwrap().anisotropic_faces = [None, None]; + assert_eq!(combined, render(scene(Vec3::Z), req, Some(environment(false, 0.0)))); +} + +#[test] +fn mirror_bright_cell_rotates_in_world_space_without_changing_background() { + let reflected = Vec3::new(0.5, 0.5, 0.5_f64.sqrt()); + let normal = Vec3::Z + reflected; + let req = request(ReflectionMode::Mirror); + assert_eq!(centre(&render(scene(normal), req.clone(), Some(environment(true, 0.0)))), expected([16.0, 8.0, 2.0])); + assert_eq!(centre(&render(scene(normal), req, Some(environment(true, std::f64::consts::FRAC_PI_2)))), [0, 0, 0, 255]); +} + +#[test] +fn unsupported_diffuse_rough_hdr_refuses_and_selector_capacities_remain_accounted() { + let req = request(ReflectionMode::RoughSpecular); + let options = req.raytrace.clone().unwrap(); + let mut invalid = scene(Vec3::Z); + invalid.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.5, 1.0, 1.5).unwrap()); + assert!(ImageTask::new_with_environment(invalid, req.clone(), CancelToken::default(), options.clone(), Some(environment(false, 0.0))).is_err()); + let mut invalid = scene(Vec3::Z); + invalid.meshes[0].faces.push(crate::FaceAppearance { transmission: None, face: 0, color: [255; 3], opacity: 1.0, surface: None }); + assert!(options.validate_environment_reflections(&invalid).is_err()); + let selectors = options.reflections.as_ref().unwrap(); + assert_eq!( + options.retained_bytes().unwrap(), + (selectors.bodies.capacity() * std::mem::size_of::() + selectors.bodies[0].body.capacity()) as u64 + ); + assert!(std::mem::size_of::() <= 4096, "combined task state must fit the host's admitted slot"); +} + +#[test] +fn secondary_environment_miss_obeys_shared_work_limit_and_cancel() { + for cancel_now in [false, true] { + let req = request(ReflectionMode::Mirror); + let options = req.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(scene(Vec3::Z), req, cancel.clone(), options, Some(environment(false, 0.0))).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + break; + } + } + assert!(task.pending.as_ref().is_some_and(|p| p.bounce > 0)); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } +} + +fn anisotropic_request(mode: ReflectionMode, equal_axes: bool) -> ImageRequest { + let mut request = request(mode); + request.raytrace.as_mut().unwrap().anisotropic_faces = [ + Some(job::AnisotropicFaceOptions { + body_index: 0, + body_name: "Metal".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: job::AnisotropicOrientation::Zero, + roughness_x: if equal_axes { 1.0 } else { 0.2 }, + roughness_y: if equal_axes { 1.0 } else { 0.6 }, + }), + None, + ]; + request +} + +#[test] +fn hdr_equal_anisotropic_axes_match_isotropic_reflected_environment_bytes() { + let plain = render(scene(Vec3::Z), request(ReflectionMode::RoughSpecular), Some(environment(false, 0.0))); + let request = anisotropic_request(ReflectionMode::RoughSpecular, true); + assert_eq!(plain, render(scene(Vec3::Z), request, Some(environment(false, 0.0)))); +} + +#[test] +fn hdr_anisotropic_direct_and_mirror_combinations_refuse_before_pixels() { + for kind in 0..2 { + let mut request = anisotropic_request(ReflectionMode::RoughSpecular, false); + if kind == 0 { + request.raytrace.as_mut().unwrap().reflections = None; + } else { + request.raytrace.as_mut().unwrap().reflections.as_mut().unwrap().bodies[0].mode = ReflectionMode::Mirror; + } + let options = request.raytrace.clone().unwrap(); + assert!(ImageTask::new_with_environment(scene(Vec3::Z), request, CancelToken::default(), options, Some(environment(false, 0.0))).is_err()); + } +} + +#[test] +fn hdr_anisotropic_secondary_hit_yields_before_another_debit_and_observes_cancel() { + let mut source = scene(Vec3::new(0.0, -1.0, 1.0)); + // Original planar reflector z=y, with a broad separate horizontal receiver. + let mesh = Arc::new(Mesh { + positions: vec![ + Vec3::new(-100.0, -100.0, 10.0), + Vec3::new(-100.0, 100.0, 10.0), + Vec3::new(100.0, 100.0, 10.0), + Vec3::new(100.0, -100.0, 10.0), + ], + normals: vec![-Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + source.bounds = source.bounds.union(&mesh.bounds()); + source.meshes.push(crate::ProductMesh { + transmission: None, + name: "Receiver".into(), + mesh, + color: [240, 80, 20], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + let mut request = anisotropic_request(ReflectionMode::RoughSpecular, false); + request.camera.set_view(crate::StandardView::Front); + request.width = 1; + request.height = 1; + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new_with_environment(source, request, cancel.clone(), options, Some(environment(false, 0.0))).unwrap(); + while task.bvh.is_none() { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + let mut secondary_hit = false; + for _ in 0..200_000 { + let tracing_secondary = task.pending.as_ref().is_some_and(|p| p.bounce > 0 && p.hit.is_none()); + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 1, "secondary hit completion fell through into shading"); + if tracing_secondary && task.pending.as_ref().is_some_and(|p| p.hit.is_some()) { + secondary_hit = true; + break; + } + } + assert!(secondary_hit); + let before = task.work.used(); + assert!(matches!(task.step(4).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/image.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/image.rs new file mode 100644 index 000000000..25e7e4ad8 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/image.rs @@ -0,0 +1,2573 @@ +//! Opt-in opaque direct image integration; immutable world geometry, one host reservation. +use super::anisotropic_faces::{self, PlanarTarget}; +use super::bvh::TraceCursor; +use super::dielectric::{self, Certificate, MAX_BOUNDARIES, MAX_OVERRIDES, MAX_PATHS}; +use super::lighting::{DirectionalLight, Lighting, StudioPreset, map_to_display}; +use super::prepared::{PreparedPrimitive, PreparedScene, SharedHit}; +use super::progressive::{self, Progressive}; +use super::reflection; +use super::{BuildLimits, Bvh, BvhBuilder, Ray, TraceError, Triangle, WorkBudget}; +use crate::job::{self, Admission, CancelToken, ErrorCode, ImageRequest, JobError, Phase, Progress, RaytraceOptions, TaskPoll}; +use crate::{ + ProductScene, + film::primary::PrimaryFilm, + surface::{OpaqueSurface, srgb8_to_linear}, +}; +use solidcraft_geom::{Vec3, srgb::encode8}; + +#[cfg(test)] +#[path = "environment_image_tests.rs"] +mod environment_image_tests; + +#[cfg(test)] +#[path = "environment_reflection_tests.rs"] +mod environment_reflection_tests; + +#[cfg(test)] +#[path = "anisotropic_reflection_image_tests.rs"] +mod anisotropic_reflection_tests; + +fn error(e: TraceError) -> JobError { + let code = match e { + TraceError::Cancelled => ErrorCode::Cancelled, + TraceError::MemoryLimit | TraceError::WorkLimit => ErrorCode::LimitExceeded, + TraceError::AllocationFailed => ErrorCode::AllocationFailed, + TraceError::InvalidInput(_) => ErrorCode::InvalidScene, + _ => ErrorCode::Internal, + }; + JobError::new(code, e.to_string()) +} +fn invalid(message: &'static str) -> JobError { + JobError::new(ErrorCode::InvalidScene, message) +} +fn limits(budget: job::CpuBudget) -> BuildLimits { + let limits = budget.limits(); + BuildLimits { + max_triangles: limits.max_triangles as usize, + max_memory_bytes: limits.max_job_bytes, + max_work: limits.max_work_units, + ..Default::default() + } +} +fn lighting(options: &RaytraceOptions) -> job::Result { + options.validate()?; + if let Some(preset) = options.preset { + let preset = match preset { + job::LightingPreset::Neutral => StudioPreset::Neutral, + job::LightingPreset::WarmCool => StudioPreset::WarmCool, + job::LightingPreset::KeyRim => StudioPreset::KeyRim, + }; + return Lighting::preset(preset).map_err(error); + } + match &options.lights { + None => Ok(Lighting::studio_default()), + Some(inputs) => { + let mut lights = Vec::new(); + lights.try_reserve_exact(inputs.len()).map_err(|_| error(TraceError::AllocationFailed))?; + for l in inputs { + lights.push( + DirectionalLight::new( + Vec3::new(l.direction[0], l.direction[1], l.direction[2]), + Vec3::new(l.color[0], l.color[1], l.color[2]), + l.intensity, + ) + .map_err(error)?, + ); + } + Lighting::new(lights).map_err(error) + } + } +} +type Look = PreparedPrimitive; + +fn certificates( + scene: &ProductScene, + options: &RaytraceOptions, + nested: bool, +) -> job::Result<([Option; MAX_OVERRIDES], [Option; MAX_OVERRIDES])> { + let mut result = [None; MAX_OVERRIDES]; + for (slot, input) in result.iter_mut().zip(&options.dielectrics) { + *slot = Some(dielectric::certify(scene, input).map_err(error)?); + } + let parents = dielectric::parents(&result, nested).map_err(error)?; + // Sheets within volumes are unsupported. Conservatively use the admitted + // tiny sheet's bounds, rather than pretending to resolve medium nesting. + for (i, certificate) in result.iter().enumerate() { + if let Some(Certificate::ClosedBox(a)) = certificate { + for (j, other) in result.iter().enumerate() { + if i != j && matches!(other, Some(Certificate::ThinSheet)) { + let input = options.dielectrics.get(j).ok_or_else(|| invalid("sheet override index"))?; + let body = scene.meshes.get(input.body_index).ok_or_else(|| invalid("sheet body index"))?; + let bounds = body.mesh.bounds(); + if dielectric::overlaps(*a, super::Bounds::new(bounds.min, bounds.max).map_err(error)?) { + return Err(invalid("thin sheets touching or inside dielectric volumes are unsupported")); + } + } + } + } + } + Ok((result, parents)) +} + +/// Private construction policy; protected admission is selected before allocations. +#[derive(Clone, Copy)] +enum PreviewPolicy { + Legacy, + Shared(job::PartialPreviewPlan), + Protected(job::ProtectedPreviewPlan), +} +impl PreviewPolicy { + fn partial_plan(self) -> Option { + match self { + Self::Legacy => None, + Self::Shared(plan) => Some(plan), + Self::Protected(plan) => Some(plan.preview_plan()), + } + } +} + +fn committed_frontier(frontier: crate::film::primary::PartialFrontier) -> job::Result { + let pixels = u64::try_from(frontier.pixels).map_err(|_| error(TraceError::MemoryLimit))?; + let prefix = u64::try_from(frontier.updated_prefix).map_err(|_| error(TraceError::MemoryLimit))?; + u64::from(frontier.completed_passes).checked_mul(pixels).and_then(|n| n.checked_add(prefix)).ok_or_else(|| error(TraceError::WorkLimit)) +} + +pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> job::Result { + admit_with_nested(scene, request, options, false) +} + +pub(crate) fn admit_with_nested(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions, nested: bool) -> job::Result { + admit_with_policy(scene, request, options, nested, PreviewPolicy::Legacy) +} + +pub(crate) fn admit_with_partial_preview( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + nested: bool, + plan: job::PartialPreviewPlan, +) -> job::Result { + admit_with_policy(scene, request, options, nested, PreviewPolicy::Shared(plan)) +} + +pub(crate) fn admit_with_protected_partial_preview( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + nested: bool, + plan: job::ProtectedPreviewPlan, +) -> job::Result { + admit_with_policy(scene, request, options, nested, PreviewPolicy::Protected(plan)) +} + +fn admit_with_policy( + scene: &ProductScene, + request: &ImageRequest, + options: &RaytraceOptions, + nested: bool, + policy: PreviewPolicy, +) -> job::Result { + if let PreviewPolicy::Protected(plan) = policy { + plan.validate()?; + let progressive = + options.progressive.ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected feedback requires progressive CPU sampling"))?; + if plan != job::ProtectedPreviewPlan::with_cadence(request.width, request.height, progressive.samples_per_pixel, options.budget, request.cpu_progressive_every_pass)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan differs from actual source sampling or budget")); + } + } + let partial = policy.partial_plan(); + if let Some(plan) = partial { + plan.validate()?; + if plan != job::PartialPreviewPlan::new(request.width, request.height)? + || options.progressive.is_none() + || request.environment.is_some() + || request.textures.is_some() + || scene.has_transmission() + { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview requires the exact CPU progressive source plan")); + } + } + options.validate()?; + if options.directional_shadow_transmission && nested { + return Err(invalid("directional shadow transmission does not support nested media")); + } + if let Some(original) = &request.raytrace { + original.validate()?; + } + if request.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()) != options { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace options disagree with image request")); + } + if request.integrator != job::Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "raytrace task requires raytrace integrator")); + } + if request.transparent_background { + return Err(invalid("raytrace supports opaque backgrounds only")); + } + if let Some(progressive) = options.progressive { + progressive.validate_image_with_budget(request.width, request.height, options.budget)?; + } + let mut a = job::image::admit_raytrace_source(scene, request, options.budget)?; + let r = options.reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples); + u64::from(request.width) + .checked_mul(u64::from(request.height)) + .and_then(|n| n.checked_mul(u64::from(options.primary_samples))) + .and_then(|n| n.checked_mul(u64::from(r))) + .ok_or_else(|| invalid("spatial attempt count overflow"))?; + for (index, body) in scene.meshes.iter().enumerate() { + if body.opacity != 1.0 || body.faces.iter().any(|f| f.opacity != 1.0) { + return Err(invalid("raytrace requires opaque body and face appearances")); + } + let has_coat = body.surface.is_some_and(|surface| surface.clear_coat().is_some()) + || body.faces.iter().any(|face| face.surface.is_some_and(|surface| surface.clear_coat().is_some())); + let selected_transport = options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == body.name)) + || options.anisotropic_faces.iter().flatten().any(|entry| entry.body_index == index) + || options.dielectrics.iter().any(|entry| entry.body_index == index); + if has_coat && selected_transport { + return Err(invalid("CPU reflection, anisotropy and dielectric overrides do not support clear-coat transport")); + } + } + if let Some(reflections) = &options.reflections { + for override_ in &reflections.bodies { + let count = scene.meshes.iter().filter(|body| body.name == override_.body).count(); + if count != 1 { + return Err(JobError::new(ErrorCode::InvalidRequest, "reflection body must resolve to exactly one captured body")); + } + } + } + anisotropic_faces::prepare(scene, options, || Ok(()))?; + certificates(scene, options, nested)?; + for input in &options.dielectrics { + if options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|v| v.body == input.body_name)) + || options.anisotropic_faces.iter().flatten().any(|v| v.body_index == input.body_index) + || options.emissions.iter().flatten().any(|v| v.body_index == input.body_index) + { + return Err(invalid("dielectric boundaries cannot also select opaque reflection, anisotropy or emission")); + } + if let Some(values) = &options.surface_effects { + for value in values.iter().filter(|v| v.body == input.body_name) { + if !value.prepare()?.is_identity() { + return Err(invalid("nonidentity surface effects on dielectric boundaries are unsupported")); + } + } + } + } + if let Some(values) = &options.surface_effects { + for value in values { + let mut bodies = scene.meshes.iter().enumerate().filter(|(_, body)| body.name == value.body); + let (index, _) = bodies.next().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "surface effect body missing"))?; + if bodies.next().is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "surface effect body must resolve uniquely")); + } + if !value.prepare()?.is_identity() && options.anisotropic_faces.iter().flatten().any(|target| target.body_index == index) { + return Err(JobError::new(ErrorCode::InvalidRequest, "surface effects on a certified anisotropic body are not supported")); + } + } + } + if let Some(values) = &options.emissions { + for value in values { + if scene.meshes.get(value.body_index).is_none_or(|body| body.name != value.body) { + return Err(invalid("surface emission target does not match captured body index and name")); + } + } + } + // Bill each task-owned options copy and the prepared emission vector in addition + // to the unchanged baseline estimate. Record metadata has its independent lease. + let emission_bytes = options + .retained_emission_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_emission_bytes)?) + .and_then(|v| { + v.checked_add(options.emissions.as_ref().map_or(0, Vec::len) as u64 * std::mem::size_of::<(usize, super::emission::Emission)>() as u64) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + // The task owns two independent options copies plus its prepared effect vector. + // The original request Record remains billed by the same retained_bytes sum. + let effect_bytes = options + .retained_surface_effect_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_surface_effect_bytes)?) + .and_then(|v| { + v.checked_add( + options.surface_effects.as_ref().map_or(0, Vec::len) as u64 + * std::mem::size_of::<(usize, crate::surface_patterns::PreparedEffect)>() as u64, + ) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let optical_bytes = options + .retained_dielectric_bytes()? + .checked_add(request.raytrace.as_ref().map_or(Ok(0), RaytraceOptions::retained_dielectric_bytes)?) + .and_then(|v| v.checked_add(if options.dielectrics.is_empty() { 0 } else { std::mem::size_of::() as u64 })) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + let n = usize::try_from(a.triangles).map_err(|_| error(TraceError::MemoryLimit))?; + let film_bytes = if let Some(progressive) = options.progressive { + let checkpoint = a.encoded_limit.checked_add(job::FRAME_METADATA_BYTES).ok_or_else(|| error(TraceError::MemoryLimit))?; + let previews = if let Some(plan) = partial { + plan.additional_bytes()? + } else { + u64::from(progressive.checkpoint_slots()) + .checked_mul(checkpoint) + .and_then(|bytes| bytes.checked_add(if progressive.checkpoint_slots() == 0 { 0 } else { 1024 })) + .ok_or_else(|| error(TraceError::MemoryLimit))? + }; + PrimaryFilm::required_bytes(request.width, request.height, progressive, options.budget)? + .checked_add(previews) + .and_then(|v| v.checked_add(std::mem::size_of::() as u64)) + .ok_or_else(|| error(TraceError::MemoryLimit))? + } else { + 0 + }; + let extra = BvhBuilder::required_bytes(n, n, limits(options.budget)) + .map_err(error)? + .checked_add(a.triangles.checked_mul(std::mem::size_of::() as u64).ok_or_else(|| error(TraceError::MemoryLimit))?) + .and_then(|v| v.checked_add(emission_bytes)) + .and_then(|v| v.checked_add(effect_bytes)) + .and_then(|v| v.checked_add(optical_bytes)) + .and_then(|v| v.checked_add(film_bytes)) + // The resumable pixel owns two traversal cursors. Its fallible, fixed + // heap slot is additional to the unchanged host/task-state allowance. + .and_then(|v| v.checked_add(PendingPixelSlot::required_bytes())) + .and_then(|v| { + v.checked_add(8192 + if options.reflections.is_some() || options.anisotropic_faces.iter().any(Option::is_some) { 32768 } else { 0 }) + }) + .and_then(|v| { + v.checked_add(options.area_lights.as_ref().map_or(0, Vec::capacity) as u64 * std::mem::size_of::() as u64) + }) + .and_then(|v| { + v.checked_add(options.punctual_lights.as_ref().map_or(0, Vec::capacity) as u64 * std::mem::size_of::() as u64) + }) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + // Keep the conservative raster pixel/codec estimate; add every new owned buffer. + a.preparation_bytes = a.preparation_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + a.estimated_total_bytes = a.estimated_total_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + if a.estimated_total_bytes > options.budget.limits().max_job_bytes { + return Err(error(TraceError::MemoryLimit)); + } + Ok(a) +} + +struct PendingPixel { + surface_cursor: usize, + surface_index: Option, + surface_ready: bool, + emission_cursor: usize, + punctual_index: usize, + punctual_shadow: bool, + punctual_ready: bool, + punctual_value: Vec3, + area_light: usize, + area_index: u32, + area_shadow: bool, + area_ready: bool, + area_value: Vec3, + + /// Proof from the primary generator, revoked for any selected reflector. + /// A jittered/time-varying primary generator MUST supply false. + repeatable_primary: bool, + environment_sample: u32, + environment_sum: Vec3, + environment_cursor: Option, + environment_value: Vec3, + ray: Ray, + cursor: TraceCursor, + hit: Option, + visibility: [bool; 8], + directional_transmittance: [Vec3; 8], + directional_complete: u8, + directional_active: bool, + directional_required: bool, + light: usize, + bounce: u8, + throughput: Vec3, + radiance: Vec3, +} + +/// A commit/reset may abandon neither an active connection nor an unfinished rig. +fn ensure_directional_drained(pending: Option<&PendingPixel>, lights: usize) -> job::Result<()> { + if lights > super::lighting::MAX_LIGHTS { + return Err(invalid("directional light count exceeds fixed visibility storage")); + } + let required = ((1u16 << lights) - 1) as u8; + if pending.is_some_and(|pending| pending.directional_active || (pending.directional_required && pending.directional_complete != required)) { + return Err(invalid("directional visibility connection has not drained")); + } + Ok(()) +} + +fn begin_directional_shadow( + owner: &mut dielectric::DirectVisibilityOwner, + pending: &mut PendingPixel, + ray: Ray, + work: &mut WorkBudget, + cancel: &CancelToken, +) -> job::Result<()> { + if pending.light >= super::lighting::MAX_LIGHTS || pending.directional_active { + return Err(invalid("invalid directional connection start")); + } + let bit = 1u8 << pending.light; + if pending.directional_complete & bit != 0 { + return Err(invalid("directional connection already completed")); + } + pending.directional_required = true; + owner.begin(ray, dielectric::MAX_DIRECT_CROSSINGS, work, cancel).map_err(error)?; + pending.directional_active = true; + Ok(()) +} + +/// One reusable, fallibly allocated continuation. The Vec header stays in the +/// 4096-byte host slot; its exact single-element capacity is billed by admit. +/// Keeping an empty slot between samples avoids any per-ray allocation. +struct PendingPixelSlot(Vec); + +impl PendingPixelSlot { + fn required_bytes() -> u64 { + std::mem::size_of::() as u64 + } + + fn new(cancel: &CancelToken) -> job::Result { + cancel.check()?; + let mut slot = Vec::new(); + slot.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if slot.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + cancel.check()?; + Ok(Self(slot)) + } + + fn as_ref(&self) -> Option<&PendingPixel> { + self.0.first() + } + + fn as_mut(&mut self) -> Option<&mut PendingPixel> { + self.0.first_mut() + } + + fn is_none(&self) -> bool { + self.0.is_empty() + } + + #[cfg(test)] + fn is_some(&self) -> bool { + !self.is_none() + } + + fn insert(&mut self, value: PendingPixel) -> job::Result<()> { + if self.0.capacity() != 1 || !self.0.is_empty() { + return Err(invalid("pending pixel slot is unavailable")); + } + // Capacity is already admitted and reserved: this cannot allocate. + self.0.push(value); + Ok(()) + } + + fn clear(&mut self) { + self.0.clear(); + } + + fn release(&mut self) { + self.0 = Vec::new(); + } +} + +#[derive(Clone, Copy)] +struct OpticalPath { + ray: Ray, + throughput: Vec3, + medium: Option, + /// Boundary or opaque reflection position, before the numerical spawn offset. + segment_start: Vec3, + boundaries: u8, + /// Opaque reflection depth is independent of the dielectric interface count. + bounce: u8, +} + +struct DielectricPixel { + /// A whole Fresnel tree belongs to one absolute camera sample. Fixed paths + /// keep None; work quanta and presentation never enter this identity. + camera_sample: Option<(usize, u32)>, + path: OpticalPath, + stack: [Option; MAX_BOUNDARIES as usize + 1], + stack_len: usize, + paths: u16, + primary_check: usize, + selector: usize, + selected: Option, + ready: bool, +} + +/// At most2 crossings per certified convex box and1 per certified planar sheet +/// on a single straight camera segment. Equal indices preserve direction; no +/// selected opaque reflector may generate another segment. Certificates and +/// strict parent validation precede this bounded, allocation-free policy. +fn straight_boundary_limit(options: &RaytraceOptions, certificates: &[Option; MAX_OVERRIDES]) -> job::Result> { + if options.dielectrics.is_empty() + || options.dielectrics.iter().any(|input| input.ior != 1.0) + || options.reflections.as_ref().is_some_and(|r| !r.bodies.is_empty()) + { + return Ok(None); + } + let mut limit = 0_u8; + for (index, input) in options.dielectrics.iter().enumerate() { + let certificate = certificates.get(index).copied().flatten().ok_or_else(|| invalid("missing straight optical certificate"))?; + let crossings = match (input.boundary, certificate) { + (job::DielectricBoundary::ClosedBox, Certificate::ClosedBox(_)) => 2, + (job::DielectricBoundary::ThinSheet, Certificate::ThinSheet) => 1, + _ => return Err(invalid("straight optical certificate disagrees with boundary")), + }; + limit = limit.checked_add(crossings).filter(|n| *n <= 16).ok_or_else(|| invalid("straight optical crossing bound exceeds sixteen"))?; + } + Ok(Some(limit)) +} + +/// One fallibly reserved optional slot. Branches do not copy PendingPixel, own +/// lighting state, encode pixels, or allocate outside the existing job reservation. +struct OpticalTask { + /// None retains the original eight-event branching model unchanged. + straight_limit: Option, + /// Captured runtime dielectric policy; fixed and progressive use the same transport. + deterministic_tir: bool, + /// Actual deterministic continuations CREATED, not completed rays or paths. + tir_continuations: u64, + certificates: [Option; MAX_OVERRIDES], + parents: [Option; MAX_OVERRIDES], + nested: bool, + pending: Option, +} + +impl DielectricPixel { + fn new(ray: Ray) -> Self { + Self { + path: OpticalPath { ray, throughput: Vec3::new(1.0, 1.0, 1.0), medium: None, segment_start: ray.origin(), boundaries: 0, bounce: 0 }, + camera_sample: None, + stack: [None; MAX_BOUNDARIES as usize + 1], + stack_len: 0, + paths: 1, + primary_check: 0, + selector: 0, + selected: None, + ready: false, + } + } + + fn check_camera_sample(&self, actual: Option<(usize, u32)>) -> job::Result<()> { + if self.camera_sample != actual { + return Err(invalid("optical tree differs from its absolute camera sample")); + } + Ok(()) + } + + fn push(&mut self, path: OpticalPath) -> job::Result<()> { + if !bounded_radiance(path.throughput) { + return Err(invalid("dielectric branch throughput exceeds finite bound")); + } + if path.throughput == Vec3::ZERO { + return Ok(()); + } + if self.paths >= MAX_PATHS { + return Err(error(TraceError::WorkLimit)); + } + *self.stack.get_mut(self.stack_len).ok_or_else(|| error(TraceError::MemoryLimit))? = Some(path); + self.stack_len += 1; + self.paths += 1; + Ok(()) + } + + fn advance(&mut self) -> job::Result { + if self.stack_len == 0 { + return Ok(false); + } + self.stack_len -= 1; + self.path = self.stack.get_mut(self.stack_len).and_then(Option::take).ok_or_else(|| invalid("optical path stack"))?; + self.selector = 0; + self.selected = None; + self.ready = false; + Ok(true) + } +} + +/// Reset only per-hit transport state; retain the shared sum across Fresnel leaves. +fn resume_optical_path(pending: &mut PendingPixel, path: OpticalPath, lights: usize) -> job::Result<()> { + ensure_directional_drained(Some(pending), lights)?; + pending.ray = path.ray; + pending.throughput = path.throughput; + pending.bounce = path.bounce; + pending.repeatable_primary = false; + pending.cursor = TraceCursor::new(path.ray, false); + pending.hit = None; + pending.surface_cursor = 0; + pending.surface_index = None; + pending.surface_ready = false; + pending.emission_cursor = 0; + pending.light = 0; + pending.visibility = [true; 8]; + pending.directional_transmittance = [Vec3::ZERO; 8]; + pending.directional_complete = 0; + pending.directional_active = false; + pending.directional_required = false; + pending.punctual_index = 0; + pending.punctual_shadow = false; + pending.punctual_ready = false; + pending.punctual_value = Vec3::ZERO; + pending.area_light = 0; + pending.area_index = 0; + pending.area_shadow = false; + pending.area_ready = false; + pending.area_value = Vec3::ZERO; + pending.environment_sample = 0; + pending.environment_sum = Vec3::ZERO; + pending.environment_cursor = None; + pending.environment_value = Vec3::ZERO; + Ok(()) +} + +pub struct ImageTask { + punctual_diagnostics: job::PunctualDiagnostics, + progressive: Option, + last_pass_boundary: u32, + optical: Vec, + anisotropic_targets: [Option; 2], + environment: Option, + visibility_owner: dielectric::DirectVisibilityOwner, + request: ImageRequest, + cancel: CancelToken, + admission: Admission, + lights: Lighting, + emissions: Vec<(usize, super::emission::Emission)>, + effects: Vec<(usize, crate::surface_patterns::PreparedEffect)>, + work: WorkBudget, + clip: (f64, f64), + triangles: Vec, + looks: Vec, + body: usize, + triangle: usize, + face_cursor: usize, + chosen: Option, + builder: Option, + bvh: Option, + build_used: u64, + pixels: Vec, + pixel: usize, + sample: u8, + spatial: u8, + primary_coverage: u16, + spatial_radiance: Vec3, + finish_spatial: bool, + emit_spatial_pixel: bool, + pixel_radiance: Vec3, + pending: PendingPixelSlot, + encoder: Option, + done: bool, +} +// Same host slot: a future feature build must prove the actual target layout. +const _: [(); 1] = [(); (std::mem::size_of::() <= 4096) as usize]; + +/// CPU continuations. Preview bytes are complete PNGs but acquire a transferable +/// host lease and identity only when the owning host publishes them. +pub enum ImagePoll { + Pending(Progress), + Preview { png: Vec, samples_per_pixel: u32 }, + Complete(Vec), +} + +/// Additive host-only poll; the public legacy ImagePoll contract is unchanged. +pub(crate) enum PartialImagePoll { + Pending(Progress), + Complete(Vec), + Preview { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, +} + +pub(crate) enum PartialBegin { + Started, + Exhausted, +} + +enum ImageAdvance { + Legacy(ImagePoll), + Partial { png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64 }, +} + +impl ImageTask { + pub fn punctual_diagnostics(&self) -> Option { + (!self.punctual_diagnostics.is_empty()).then_some(self.punctual_diagnostics) + } + + pub fn new(scene: ProductScene, request: ImageRequest, cancel: CancelToken, options: RaytraceOptions) -> job::Result { + Self::new_with_environment(scene, request, cancel, options, None) + } + pub fn new_with_environment( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + ) -> job::Result { + Self::new_with_environment_and_nested(scene, request, cancel, options, input, false) + } + + pub(crate) fn new_with_environment_and_nested( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + ) -> job::Result { + Self::new_with_policy(scene, request, cancel, options, input, nested, PreviewPolicy::Legacy) + } + + /// Compatibility helper for the original five regression sources. Activate + /// the real serialized production policy before ordinary admission/construction. + #[cfg(test)] + fn new_with_deterministic_tir( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + nested: bool, + ) -> job::Result { + let mut options = options; + options.dielectric_transport = job::CpuDielectricTransport::StrictTir; + let mut request = request; + request.raytrace = Some(options.clone()); + Self::new_with_environment_and_nested(scene, request, cancel, options, None, nested) + } + + pub(crate) fn new_with_environment_and_nested_and_partial( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + plan: job::PartialPreviewPlan, + ) -> job::Result { + Self::new_with_policy(scene, request, cancel, options, input, nested, PreviewPolicy::Shared(plan)) + } + + pub(crate) fn new_with_environment_and_nested_and_protected_partial( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + plan: job::ProtectedPreviewPlan, + ) -> job::Result { + Self::new_with_policy(scene, request, cancel, options, input, nested, PreviewPolicy::Protected(plan)) + } + + fn new_with_policy( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + options: RaytraceOptions, + input: Option, + nested: bool, + policy: PreviewPolicy, + ) -> job::Result { + cancel.check()?; + if options.directional_shadow_transmission && input.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "directional shadow transmission does not support HDR environments")); + } + let mut admission = admit_with_policy(&scene, &request, &options, nested, policy)?; + let partial = policy.partial_plan(); + let mut optical = Vec::new(); + if !options.dielectrics.is_empty() { + let (certificates, parents) = certificates(&scene, &options, nested)?; + let straight_limit = straight_boundary_limit(&options, &certificates)?; + optical.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if optical.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } + optical.push(OpticalTask { + straight_limit, + deterministic_tir: options.dielectric_transport == job::CpuDielectricTransport::StrictTir, + tir_continuations: 0, + certificates, + parents, + nested, + pending: None, + }); + } + if input.is_some() { + options.validate_environment_reflections(&scene)?; + } + let extra = input.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(environment_error)?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(extra) + .filter(|v| *v <= options.budget.limits().max_job_bytes) + .ok_or_else(|| error(TraceError::MemoryLimit))?; + admission.preparation_bytes = admission.preparation_bytes.checked_add(extra).ok_or_else(|| error(TraceError::MemoryLimit))?; + let environment = input.map(|e| e.begin()).transpose().map_err(environment_error)?; + let lights = lighting(&options)?; + let mut work = match policy { + PreviewPolicy::Protected(plan) => WorkBudget::new_protected(plan), + PreviewPolicy::Legacy | PreviewPolicy::Shared(_) => WorkBudget::new(options.budget.limits().max_work_units), + } + .map_err(error)?; + let anisotropic_targets = anisotropic_faces::prepare(&scene, &options, || work.tick(&cancel).map_err(error))?; + let mut effects = Vec::new(); + if let Some(values) = &options.surface_effects { + effects.try_reserve_exact(values.len()).map_err(|_| error(TraceError::AllocationFailed))?; + if effects.capacity() != values.len() { + return Err(error(TraceError::MemoryLimit)); + } + for value in values { + work.tick(&cancel).map_err(error)?; + let effect = value.prepare()?; + let index = scene + .meshes + .iter() + .position(|body| body.name == value.body) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "surface effect body missing"))?; + // Identity is omitted to preserve the existing pixel path and bytes. + if !effect.is_identity() { + effects.push((index, effect)); + } + } + } + let mut emissions = Vec::new(); + if let Some(values) = &options.emissions { + emissions.try_reserve_exact(values.len()).map_err(|_| error(TraceError::AllocationFailed))?; + if emissions.capacity() != values.len() { + return Err(error(TraceError::MemoryLimit)); + } + for value in values { + work.tick(&cancel).map_err(error)?; + // Skip zero terms to preserve the baseline floating-point path exactly. + if value.strength != 0.0 && value.color.iter().any(|v| *v != 0.0) { + emissions.push((value.body_index, super::emission::Emission::new(value)?)); + } + } + } + let radius = + if scene.meshes.is_empty() { 10.0 } else { scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(request.camera.target) }; + if !radius.is_finite() { + return Err(invalid("invalid product bounds")); + } + let clip = request.camera.clip(radius); + let mut triangles = Vec::new(); + let mut looks = Vec::new(); + let mut pixels = Vec::new(); + triangles.try_reserve_exact(admission.triangles as usize).map_err(|_| error(TraceError::AllocationFailed))?; + looks.try_reserve_exact(admission.triangles as usize).map_err(|_| error(TraceError::AllocationFailed))?; + pixels.try_reserve_exact(request.width as usize * request.height as usize * 4).map_err(|_| error(TraceError::AllocationFailed))?; + // Allocator capacities are checked, not assumed equal to requested capacities. + let actual = BvhBuilder::required_bytes(admission.triangles as usize, triangles.capacity(), limits(options.budget)).map_err(error)?; + if actual != BvhBuilder::required_bytes(admission.triangles as usize, admission.triangles as usize, limits(options.budget)).map_err(error)? + || looks.capacity() != admission.triangles as usize + || pixels.capacity() != request.width as usize * request.height as usize * 4 + { + return Err(error(TraceError::MemoryLimit)); + } + let pending = PendingPixelSlot::new(&cancel)?; + let budget = options.budget; + let progressive = options + .progressive + .map(|options| -> job::Result { + let bytes = PrimaryFilm::required_bytes(request.width, request.height, options, budget)?; + let film = PrimaryFilm::new(request.width, request.height, options, bytes, &cancel, budget)?; + Ok(Progressive { film, options, resolving: false, resolve_pixel: 0, partial_plan: partial, partial: None, last_partial: None }) + }) + .transpose()?; + Ok(Self { + punctual_diagnostics: Default::default(), + progressive, + last_pass_boundary: 0, + optical, + anisotropic_targets, + environment, + visibility_owner: dielectric::DirectVisibilityOwner::new(scene, options), + request, + cancel, + admission, + lights, + emissions, + effects, + clip, + work, + triangles, + looks, + body: 0, + triangle: 0, + face_cursor: 0, + chosen: None, + builder: None, + bvh: None, + build_used: 0, + pixels, + pixel: 0, + sample: 0, + spatial: 0, + primary_coverage: 0, + spatial_radiance: Vec3::ZERO, + finish_spatial: false, + emit_spatial_pixel: false, + pixel_radiance: Vec3::ZERO, + pending, + encoder: None, + done: false, + }) + } + pub fn progress(&self) -> Progress { + let (phase, done, total) = if self.done { + (Phase::Completed, 1, 1) + } else if let Some(partial) = self.progressive.as_ref().and_then(|p| p.partial.as_ref()) { + if let Some(encoder) = &self.encoder { + (Phase::Encoding, encoder.row() as u64, u64::from(partial.plan.height())) + } else { + (Phase::Encoding, partial.next as u64, partial.plan.pixels()) + } + } else if let Some(e) = &self.encoder { + (Phase::Encoding, e.row() as u64, self.request.height as u64) + } else if let Some(progressive) = &self.progressive { + let count = u64::from(self.request.width) * u64::from(self.request.height); + if !progressive.film.ready() { + (Phase::Preparing, progressive.film.initialized() as u64, count) + } else if progressive.resolving { + (Phase::Encoding, progressive.resolve_pixel as u64, count) + } else if self.bvh.is_some() { + let partial = if self.pixel as u64 == count { 0 } else { self.pixel as u64 }; + (Phase::Running, u64::from(progressive.film.samples()) * count + partial, u64::from(progressive.options.samples_per_pixel) * count) + } else { + (Phase::Preparing, self.triangles.len() as u64, self.admission.triangles) + } + } else if self.bvh.is_some() { + (Phase::Running, self.pixel as u64, self.request.width as u64 * self.request.height as u64) + } else { + (Phase::Preparing, self.triangles.len() as u64, self.admission.triangles) + }; + Progress { phase, done, total } + } + fn prepare_one(&mut self) -> job::Result<()> { + self.work.tick(&self.cancel).map_err(error)?; + let Some(body) = self.visibility_owner.source().meshes.get(self.body) else { + let triangles = std::mem::take(&mut self.triangles); + let expected = + BvhBuilder::required_bytes(triangles.len(), triangles.capacity(), limits(self.visibility_owner.options().budget)).map_err(error)?; + let builder = BvhBuilder::new(triangles, limits(self.visibility_owner.options().budget), &self.cancel).map_err(error)?; + if builder.admitted_bytes() > expected { + return Err(error(TraceError::MemoryLimit)); + } + self.builder = Some(builder); + return Ok(()); + }; + let Some(indices) = body.mesh.triangles.get(self.triangle) else { + self.body += 1; + self.triangle = 0; + return Ok(()); + }; + let mut vertices = [Vec3::ZERO; 3]; + let mut normals = [Vec3::ZERO; 3]; + for ((p, n), i) in vertices.iter_mut().zip(normals.iter_mut()).zip(indices) { + *p = *body.mesh.positions.get(*i as usize).ok_or_else(|| invalid("triangle vertex index"))?; + *n = body.mesh.normals.get(*i as usize).copied().unwrap_or(Vec3::ZERO); + } + let face = body.mesh.tri_face.get(self.triangle).copied(); + let mut color = body.color; + let mut surface = body.surface; + if let Some(look) = body.faces.get(self.face_cursor) { + self.face_cursor += 1; + if Some(look.face) == face { + self.chosen = Some(look.clone()); + self.face_cursor = body.faces.len(); + } else { + return Ok(()); + } + } + if let Some(look) = self.chosen.take() { + color = look.color; + surface = look.surface; + } + self.face_cursor = 0; + let surface = match surface { + Some(s) => s, + None => OpaqueSurface::new(Vec3::new(srgb8_to_linear(color[0]), srgb8_to_linear(color[1]), srgb8_to_linear(color[2])), 0.0, 0.7, 1.5) + .map_err(|_| invalid("invalid scalar surface"))?, + }; + self.triangles.push(Triangle::new(vertices).map_err(error)?); + self.looks.push(Look { body_index: self.body, face, surface, normals, vertices }); + self.triangle += 1; + Ok(()) + } + fn sample_count(&self) -> u8 { + self.visibility_owner.options().reflections.as_ref().filter(|r| !r.bodies.is_empty()).map_or(1, |r| r.samples) + } + fn finish_sample(&mut self, radiance: Vec3) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + // A Fresnel leaf is not a camera observation. The existing transport + // drains every reflected/transmitted branch into one linear sum first. + // Reject a premature commit rather than averaging branches into film. + if self.progressive.is_some() && self.optical.first().is_some_and(|o| o.pending.is_some()) { + return Err(invalid("progressive film cannot commit an undrained optical tree")); + } + if let Some(progressive) = &mut self.progressive { + if self.primary_coverage > 1 { + return Err(invalid("progressive camera sample has duplicate primary coverage")); + } + let ordinal = progressive.film.samples(); + progressive.film.add(self.pixel, ordinal, [radiance.x, radiance.y, radiance.z], self.primary_coverage == 1, &self.cancel, &mut || { + self.work.tick(&self.cancel).map_err(error) + })?; + self.pending.clear(); + self.primary_coverage = 0; + self.pixel += 1; + return Ok(()); + } + if self.visibility_owner.options().primary_samples != 1 { + return self.finish_spatial_sample(radiance); + } + // Only the current fixed-centre, nonselected primary path is identical + // across reflection samples: directional inputs and the environment's + // fixed u-grid do not depend on self.sample, and this path never bounces. + // Secondary nonselected hits and selected null samples still require R. + let repeats = + if self.sample == 0 && self.pending.as_ref().is_some_and(|p| p.repeatable_primary && p.bounce == 0) { self.sample_count() } else { 1 }; + // Reuse the shading result, but retain the original addition order, + // per-add bound and final divisor exactly. At most64 scalar additions, + // no repeated BVH/BSDF/environment work or new allocation/work budget. + for _ in 0..repeats { + self.pixel_radiance += radiance; + if !self.pixel_radiance.is_finite() + || [self.pixel_radiance.x, self.pixel_radiance.y, self.pixel_radiance.z].into_iter().any(|v| !(0.0..=1e12).contains(&v)) + { + return Err(invalid("reflection radiance exceeds finite transport bound")); + } + self.sample += 1; + } + self.pending.clear(); + if self.sample == self.sample_count() { + let display = map_to_display(self.pixel_radiance / self.sample as f64, self.visibility_owner.options().exposure_ev).map_err(error)?; + self.pixels.extend_from_slice(&[encode8(display.x), encode8(display.y), encode8(display.z), 255]); + self.pixel += 1; + self.sample = 0; + self.pixel_radiance = Vec3::ZERO; + } + Ok(()) + } + fn finish_spatial_sample(&mut self, radiance: Vec3) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + // Same per-R-add finite bound and denominator, including zero/null events. + self.pixel_radiance += radiance; + if !bounded_radiance(self.pixel_radiance) { + return Err(invalid("reflection radiance exceeds finite transport bound")); + } + self.sample = self.sample.checked_add(1).ok_or_else(|| invalid("reflection sample overflow"))?; + if self.sample > self.sample_count() { + return Err(invalid("reflection sample count exceeded")); + } + self.finish_spatial = self.sample == self.sample_count(); + let retain = !self.finish_spatial && self.pending.as_ref().is_some_and(|p| p.repeatable_primary && p.bounce == 0 && p.hit.is_some()); + if retain { + // A completed primary, never a traversal/shading intermediate. The + // existing light cursor has no other len+1 state (at most 8 lights). + let completed = self.lights.lights().len() + 1; + self.pending.as_mut().ok_or_else(|| invalid("missing reusable primary"))?.light = completed; + } else { + self.pending.clear(); + } + Ok(()) + } + fn spatial_transition(&mut self) -> job::Result { + if self.finish_spatial { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + self.work.tick(&self.cancel).map_err(error)?; + self.spatial_radiance += + self.pixel_radiance / f64::from(self.sample_count()) / f64::from(self.visibility_owner.options().primary_samples); + if !bounded_radiance(self.spatial_radiance) { + return Err(invalid("spatial radiance exceeds finite transport bound")); + } + self.pixel_radiance = Vec3::ZERO; + self.sample = 0; + self.spatial = self.spatial.checked_add(1).ok_or_else(|| invalid("spatial sample overflow"))?; + self.finish_spatial = false; + self.emit_spatial_pixel = self.spatial == self.visibility_owner.options().primary_samples; + return Ok(true); + } + if self.emit_spatial_pixel { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + self.work.tick(&self.cancel).map_err(error)?; + let attempts = u16::from(self.visibility_owner.options().primary_samples) + .checked_mul(u16::from(self.sample_count())) + .filter(|n| *n <= 1024) + .ok_or_else(|| invalid("spatial coverage bound"))?; + let rgba = composite_spatial( + self.spatial_radiance, + u32::from(self.primary_coverage), + u32::from(attempts), + self.request.background, + self.visibility_owner.options().exposure_ev, + )?; + self.cancel.check()?; + self.pixels.extend_from_slice(&rgba); + self.pixel += 1; + self.spatial = 0; + self.primary_coverage = 0; + self.spatial_radiance = Vec3::ZERO; + self.emit_spatial_pixel = false; + return Ok(true); + } + Ok(false) + } + fn pixel_one(&mut self) -> job::Result<()> { + if self.visibility_owner.options().primary_samples != 1 && self.pending.as_ref().is_some_and(|p| p.light > self.lights.lights().len()) { + let pending = self.pending.as_ref().ok_or_else(|| invalid("missing reusable primary"))?; + if pending.light != self.lights.lights().len() + 1 + || !pending.repeatable_primary + || pending.directional_active + || pending.bounce != 0 + || pending.hit.is_none() + || self.sample == 0 + || self.sample >= self.sample_count() + || self.spatial >= self.visibility_owner.options().primary_samples + || self.finish_spatial + || self.emit_spatial_pixel + { + return Err(invalid("invalid reusable primary state")); + } + if !pending.surface_ready + || pending.surface_cursor != self.effects.len() + || pending.emission_cursor != self.emissions.len() + || pending.punctual_index != self.visibility_owner.options().punctual_lights.as_ref().map_or(0, Vec::len) + || pending.area_light != self.visibility_owner.options().area_lights.as_ref().map_or(0, Vec::len) + || pending.punctual_shadow + || pending.punctual_ready + || pending.area_shadow + || pending.area_ready + || pending.environment_cursor.is_some() + || pending.environment_sample != self.environment.as_ref().map_or(0, |e| e.samples) + { + return Err(invalid("incomplete reusable primary shading")); + } + let radiance = pending.radiance; + // One actual scalar continuation per logical R; no bulk R loop or + // fabricated traversal debit. Check cancel/limit before mutations. + self.work.tick(&self.cancel).map_err(error)?; + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing reusable primary BVH"))?; + ensure_directional_drained(Some(pending), self.lights.lights().len())?; + let shared = resolved_surface_hit( + &PreparedScene { bvh, primitives: &self.looks, source: self.visibility_owner.source() }, + pending, + &self.effects, + )?; + if self.optical.first().is_some_and(|o| o.pending.is_some()) + || self.visibility_owner.options().dielectrics.iter().any(|input| input.body_index == shared.body_index) + { + return Err(invalid("optical primary cannot reuse shading")); + } + if self.visibility_owner.options().reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == shared.body_name)) { + return Err(invalid("selected primary cannot reuse shading")); + } + self.primary_coverage = + self.primary_coverage.checked_add(1).filter(|n| *n <= 1024).ok_or_else(|| invalid("spatial coverage overflow"))?; + return self.finish_spatial_sample(radiance); + } + if self.visibility_owner.options().primary_samples != 1 && self.spatial_transition()? { + return Ok(()); + } + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing image BVH"))?; + if self.pending.is_none() { + self.work.tick(&self.cancel).map_err(error)?; + let width = self.request.width as usize; + // This proof belongs to the generator for a fixed (pixel, spatial), + // not the camera/request globally. Future per-R jitter must revoke it. + let (ray, repeatable_primary) = if let Some(progressive) = &self.progressive { + let [dx, dy] = progressive::variates(progressive.options.seed, self.pixel as u64, progressive.film.samples(), 0); + (primary_ray(&self.request, (self.pixel % width) as f64 + dx, (self.pixel / width) as f64 + dy, self.clip).map_err(error)?, false) + } else if self.visibility_owner.options().primary_samples == 1 { + // Preserve the exact legacy centre path, including its reuse proof. + (primary_ray(&self.request, (self.pixel % width) as f64 + 0.5, (self.pixel / width) as f64 + 0.5, self.clip).map_err(error)?, true) + } else { + let [dx, dy] = primary_offset(self.visibility_owner.options().primary_samples, self.spatial)?; + (primary_ray(&self.request, (self.pixel % width) as f64 + dx, (self.pixel / width) as f64 + dy, self.clip).map_err(error)?, true) + }; + if let Some(optical) = self.optical.first_mut() { + if optical.pending.is_some() { + return Err(invalid("previous optical sample was not drained")); + } + let mut state = DielectricPixel::new(ray); + state.camera_sample = self.progressive.as_ref().map(|p| (self.pixel, p.film.samples())); + optical.pending = Some(state); + } + self.pending.insert(PendingPixel { + surface_cursor: 0, + surface_index: None, + surface_ready: false, + emission_cursor: 0, + punctual_index: 0, + punctual_shadow: false, + punctual_ready: false, + punctual_value: Vec3::ZERO, + area_light: 0, + area_index: 0, + area_shadow: false, + area_ready: false, + area_value: Vec3::ZERO, + + repeatable_primary, + environment_sample: 0, + environment_sum: Vec3::ZERO, + environment_cursor: None, + environment_value: Vec3::ZERO, + ray, + cursor: TraceCursor::new(ray, false), + hit: None, + visibility: [true; 8], + directional_transmittance: [Vec3::ZERO; 8], + directional_complete: 0, + directional_active: false, + directional_required: false, + light: 0, + bounce: 0, + throughput: Vec3::new(1.0, 1.0, 1.0), + radiance: Vec3::ZERO, + })?; + return Ok(()); + } + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical primary state"))?; + state.check_camera_sample(self.progressive.as_ref().map(|p| (self.pixel, p.film.samples())))?; + if state.primary_check < self.visibility_owner.options().dielectrics.len() { + self.work.tick(&self.cancel).map_err(error)?; + if let Some(Certificate::ClosedBox(bounds)) = optical.certificates.get(state.primary_check).copied().flatten() + && (dielectric::contains(bounds, state.path.ray.origin()) || dielectric::contains(bounds, self.request.camera.eye())) + { + return Err(invalid("camera or near plane inside a dielectric volume is unsupported")); + } + state.primary_check += 1; + return Ok(()); + } + if state.primary_check != self.visibility_owner.options().dielectrics.len() { + return Err(invalid("invalid primary certificate cursor")); + } + } + if self.pending.as_ref().is_some_and(|pending| pending.directional_active) { + if !self.visibility_owner.options().directional_shadow_transmission { + return Err(invalid("directional cursor active without its runtime mode")); + } + let result = self.visibility_owner.step(&mut self.work, &self.cancel).map_err(error)?; + if let Some(transmittance) = result { + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing directional pixel state"))?; + if pending.light >= super::lighting::MAX_LIGHTS { + return Err(invalid("directional visibility light index")); + } + *pending.directional_transmittance.get_mut(pending.light).ok_or_else(|| invalid("directional visibility result index"))? = + transmittance; + pending.directional_complete |= 1u8 << pending.light; + pending.directional_active = false; + pending.light += 1; + } + return Ok(()); + } + let scene = PreparedScene { bvh, primitives: &self.looks, source: self.visibility_owner.source() }; + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing pixel state"))?; + let primary_segment = + pending.bounce == 0 && self.optical.first().and_then(|o| o.pending.as_ref()).is_none_or(|state| state.path.boundaries == 0); + if pending.hit.is_none() { + let Some(hit) = pending.cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + let Some(hit) = hit else { + if self.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|state| state.path.medium.is_some()) { + return Err(invalid("dielectric path escaped without its certified exit")); + } + if primary_segment { + if let Some(optical) = self.optical.first_mut() { + optical.pending = None; + } + if self.visibility_owner.options().primary_samples != 1 || self.progressive.is_some() { + // A miss is one of S*R attempts, never the completed pixel. + return self.finish_sample(Vec3::ZERO); + } + let [r, g, b] = self.request.background; + self.pixels.extend_from_slice(&[r, g, b, 255]); + self.pixel += 1; + self.sample = 0; + self.pixel_radiance = Vec3::ZERO; + self.pending.clear(); + return Ok(()); + } + if let Some(environment) = &self.environment { + let emitted = + environment.view().map_err(environment_error)?.radiance_linear_srgb(pending.ray.direction()).map_err(environment_error)?; + pending.radiance += multiply(pending.throughput, emitted); + } + if self.environment.is_none() + && let Some(environment) = self.visibility_owner.options().environment + { + let [r, g, b] = environment.color; + pending.radiance += multiply(pending.throughput, Vec3::new(r, g, b) * environment.intensity); + } + let radiance = pending.radiance; + if !bounded_radiance(radiance) { + return Err(invalid("secondary environment radiance exceeds finite bound")); + } + return self.finish_transport_path(radiance); + }; + if primary_segment && (self.visibility_owner.options().primary_samples != 1 || self.progressive.is_some()) { + self.primary_coverage = + self.primary_coverage.checked_add(1).filter(|n| *n <= 1024).ok_or_else(|| invalid("spatial coverage overflow"))?; + } + pending.hit = Some(hit); + pending.light = 0; + let shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + pending.repeatable_primary &= primary_segment && mode.is_none(); + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical hit state"))?; + state.selector = 0; + state.selected = None; + state.ready = false; + // Traversal consumed this continuation; selector work begins next call. + return Ok(()); + } + pending.surface_ready = self.effects.is_empty(); + if !pending.surface_ready { + // Traversal already consumed this continuation's unit. Scan one + // effect per following call, before beginning any lighting stage. + return Ok(()); + } + if self.visibility_owner.options().shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing first light"))?; + let ray = shared.spawn(light.direction()).map_err(error)?; + if self.visibility_owner.options().directional_shadow_transmission { + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + } else { + pending.cursor = TraceCursor::new(ray, true); + } + return Ok(()); + } + pending.light = self.lights.lights().len(); + return Ok(()); + } else if self.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|state| !state.ready) { + return self.dielectric_hit_one(); + } else if !pending.surface_ready { + self.work.tick(&self.cancel).map_err(error)?; + if let Some((body_index, _)) = self.effects.get(pending.surface_cursor) { + let hit = pending.hit.ok_or_else(|| invalid("missing surface effect hit"))?; + let look = self.looks.get(hit.primitive_index).ok_or_else(|| invalid("missing surface effect appearance"))?; + let index = pending.surface_cursor; + pending.surface_cursor += 1; + if *body_index == look.body_index { + pending.surface_index = Some(index); + pending.surface_cursor = self.effects.len(); + } + return Ok(()); + } + if pending.surface_cursor != self.effects.len() { + return Err(invalid("invalid surface effect scan state")); + } + pending.surface_ready = true; + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + if self.visibility_owner.options().shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing first surface light"))?; + let ray = shared.spawn(light.direction()).map_err(error)?; + if self.visibility_owner.options().directional_shadow_transmission { + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + } else { + pending.cursor = TraceCursor::new(ray, true); + } + } else { + pending.light = self.lights.lights().len(); + } + return Ok(()); + } else if pending.light < self.lights.lights().len() { + if self.visibility_owner.options().directional_shadow_transmission { + let light = self.lights.lights().get(pending.light).ok_or_else(|| invalid("missing directional light"))?; + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let ray = shared.spawn(light.direction()).map_err(error)?; + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + return Ok(()); + } + let Some(shadow) = pending.cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + *pending.visibility.get_mut(pending.light).ok_or_else(|| invalid("light visibility index"))? = shadow.is_none(); + pending.light += 1; + if let Some(light) = self.lights.lights().get(pending.light) { + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); + return Ok(()); + } + return Ok(()); + } + if let Some((body_index, emission)) = self.emissions.get(pending.emission_cursor) { + self.work.tick(&self.cancel).map_err(error)?; + let hit = pending.hit.ok_or_else(|| invalid("missing emission hit"))?; + let look = self.looks.get(hit.primitive_index).ok_or_else(|| invalid("missing emission appearance"))?; + pending.emission_cursor += 1; + if *body_index == look.body_index { + let emitted = emission.radiance(hit.geometry.geometric_normal.dot(-pending.ray.direction()) > 0.0); + pending.radiance += multiply(pending.throughput, emitted); + if !bounded_radiance(pending.radiance) { + return Err(invalid("emission path radiance exceeds finite bound")); + } + pending.emission_cursor = self.emissions.len(); + } + return Ok(()); + } + if pending.punctual_index < self.visibility_owner.options().punctual_lights.as_ref().map_or(0, Vec::len) { + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("punctual face missing"))?.face; + let target = anisotropic_faces::target_index(self.visibility_owner.options(), shared.body_index, face) + .map(|i| self.anisotropic_targets.get(i).copied().flatten().ok_or_else(|| invalid("punctual anisotropic target missing"))) + .transpose()?; + punctual_one( + pending, + self.visibility_owner.options(), + bvh, + (shared, target, mode), + &mut self.work, + &self.cancel, + &mut self.punctual_diagnostics, + )?; + return Ok(()); + } + if pending.area_light < self.visibility_owner.options().area_lights.as_ref().map_or(0, Vec::len) { + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("area face missing"))?.face; + let target = anisotropic_faces::target_index(self.visibility_owner.options(), shared.body_index, face) + .map(|i| self.anisotropic_targets.get(i).copied().flatten().ok_or_else(|| invalid("area anisotropic target missing"))) + .transpose()?; + area_one( + pending, + self.visibility_owner.options(), + bvh, + (shared, target, mode), + &mut self.work, + &self.cancel, + area_sample_key( + self.pixel as u64, + self.spatial, + self.visibility_owner.options().primary_samples, + self.progressive.as_ref().map_or(0, |progress| progress.film.samples()), + )?, + )?; + return Ok(()); + } + if let Some(cursor) = &mut pending.environment_cursor { + let Some(blocker) = cursor.step(bvh, &mut self.work, &self.cancel).map_err(error)? else { + return Ok(()); + }; + if blocker.is_none() { + pending.environment_sum += pending.environment_value; + } + pending.environment_cursor = None; + pending.environment_sample += 1; + return Ok(()); + } + if pending.light == self.lights.lights().len() { + self.work.tick(&self.cancel).map_err(error)?; + let shared = resolved_surface_hit(&scene, pending, &self.effects)?; + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + let view = -pending.ray.direction(); + let geometric = shared.oriented_geometric_normal(); + // Disjoint estimators: selected reflectors use BSDF transport to the environment; + // only nonselected opaque hits use environment next-event estimates. + if mode.is_none() + && let Some(environment) = &self.environment + { + if pending.environment_sample < environment.samples { + let side = match environment.samples { + 1 => 1, + 4 => 2, + 16 => 4, + _ => 8, + }; + let i = pending.environment_sample; + let u = if let Some(progressive) = &self.progressive { + let [dx, dy] = progressive::variates( + progressive.options.seed, + self.pixel as u64, + progressive.film.samples(), + 0x1000 + u64::from(pending.bounce) * 128 + u64::from(i), + ); + [(f64::from(i / side) + dx) / f64::from(side), (f64::from(i % side) + dy) / f64::from(side)] + } else if side == 1 { + [0.25, 0.375] + } else { + [(f64::from(i / side) + 0.5) / f64::from(side), (f64::from(i % side) + 0.5) / f64::from(side)] + }; + let sample = environment + .view() + .map_err(environment_error)? + .direct_sample_linear_srgb(u, shared.surface, shared.shading_normal, geometric, view) + .map_err(environment_error)?; + pending.environment_value = sample.contribution_linear_srgb; + if self.visibility_owner.options().shadows && sample.contribution_linear_srgb.len2() > 0.0 { + pending.environment_cursor = Some(TraceCursor::new(shared.spawn(sample.direction).map_err(error)?, true)); + } else { + pending.environment_sum += pending.environment_value; + pending.environment_sample += 1; + } + return Ok(()); + } + pending.radiance += multiply(pending.throughput, pending.environment_sum / f64::from(environment.samples)); + } + let face = self.looks.get(shared.primitive_index).ok_or_else(|| invalid("missing captured face"))?.face; + let target_index = anisotropic_faces::target_index(self.visibility_owner.options(), shared.body_index, face); + if mode != Some(job::ReflectionMode::Mirror) { + let direct = if self.visibility_owner.options().directional_shadow_transmission { + pending.directional_required = true; + ensure_directional_drained(Some(pending), self.lights.lights().len())?; + self.lights + .shade_linear_transmitted(shared.surface, shared.shading_normal, view, |index, light| { + if geometric.dot(light) <= 0.0 { + return Ok(Vec3::ZERO); + } + if index >= super::lighting::MAX_LIGHTS || pending.directional_complete & (1u8 << index) == 0 { + return Err(TraceError::Internal("directional visibility result is incomplete")); + } + pending.directional_transmittance.get(index).copied().ok_or(TraceError::Internal("directional visibility result index")) + }) + .map_err(error)? + } else { + let visible = |index: usize, light: Vec3| { + Ok(geometric.dot(light) > 0.0 && *pending.visibility.get(index).ok_or(TraceError::Internal("light visibility"))?) + }; + if let Some(index) = target_index { + self.anisotropic_targets + .get(index) + .copied() + .flatten() + .ok_or_else(|| invalid("missing certified anisotropic face"))? + .shade(&self.lights, shared.surface, geometric, view, visible) + .map_err(error)? + } else { + self.lights.shade_linear(shared.surface, shared.shading_normal, view, visible).map_err(error)? + } + }; + pending.radiance += multiply(pending.throughput, direct); + } + let max_bounces = self.visibility_owner.options().reflections.as_ref().map_or(0, |r| r.max_bounces); + if let Some(mode) = mode.filter(|_| pending.bounce < max_bounces) { + let samples = self.visibility_owner.options().reflections.as_ref().map_or(1, |r| u64::from(r.samples)); + let u = if let Some(progressive) = &self.progressive { + progressive::variates(progressive.options.seed, self.pixel as u64, progressive.film.samples(), 0x100 + u64::from(pending.bounce)) + } else if self.visibility_owner.options().primary_samples == 1 { + reflection::variates(self.pixel as u64, self.sample as u64, pending.bounce as u64, samples).map_err(error)? + } else { + let key = spatial_key(self.pixel as u64, self.spatial, self.visibility_owner.options().primary_samples)?; + reflection::variates(key, self.sample as u64, pending.bounce as u64, samples).map_err(error)? + }; + let sampled = match (mode, target_index) { + (job::ReflectionMode::Mirror, _) => reflection::mirror(shared.surface, shared.shading_normal, view), + (job::ReflectionMode::RoughSpecular, Some(index)) => self + .anisotropic_targets + .get(index) + .copied() + .flatten() + .ok_or_else(|| invalid("missing anisotropic reflection target"))? + .sample(shared.surface, geometric, view, u), + (job::ReflectionMode::RoughSpecular, None) => reflection::rough_specular(shared.surface, shared.shading_normal, view, u), + } + .map_err(error)?; + if let Some(sample) = sampled.filter(|s| s.direction.dot(geometric) > 0.0) { + pending.throughput = multiply(pending.throughput, sample.weight); + if !pending.throughput.is_finite() { + return Err(invalid("nonfinite reflection throughput")); + } + if pending.throughput.len2() > 0.0 { + pending.ray = shared.spawn(sample.direction).map_err(error)?; + pending.cursor = TraceCursor::new(pending.ray, false); + pending.hit = None; + pending.surface_cursor = 0; + pending.surface_index = None; + pending.surface_ready = false; + pending.emission_cursor = 0; + pending.light = 0; + pending.visibility = [true; 8]; + pending.directional_transmittance = [Vec3::ZERO; 8]; + pending.directional_complete = 0; + pending.directional_active = false; + pending.directional_required = false; + pending.punctual_index = 0; + pending.punctual_shadow = false; + pending.punctual_ready = false; + pending.punctual_value = Vec3::ZERO; + pending.area_light = 0; + pending.area_index = 0; + pending.area_shadow = false; + pending.area_ready = false; + pending.area_value = Vec3::ZERO; + + pending.environment_sample = 0; + pending.environment_sum = Vec3::ZERO; + pending.environment_cursor = None; + pending.environment_value = Vec3::ZERO; + pending.bounce += 1; + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing reflected optical path"))?; + state.path.ray = pending.ray; + state.path.throughput = pending.throughput; + state.path.segment_start = shared.position; + state.path.bounce = pending.bounce; + state.selector = 0; + state.selected = None; + state.ready = false; + } + return Ok(()); + } + } + } + let radiance = pending.radiance; + return self.finish_transport_path(radiance); + } + Ok(()) + } + /// Complete a transport branch. Only a drained optical stack completes one R sample. + fn finish_transport_path(&mut self, radiance: Vec3) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + if let Some(optical) = self.optical.first_mut() { + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical sample"))?; + state.check_camera_sample(self.progressive.as_ref().map(|p| (self.pixel, p.film.samples())))?; + if state.advance()? { + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing optical continuation"))?; + resume_optical_path(pending, state.path, self.lights.lights().len())?; + return Ok(()); + } + optical.pending = None; + } + self.finish_sample(radiance) + } + + /// Each selector and each interface is a separate charged continuation. Traversal has + /// already yielded with the captured hit, and opaque hits rejoin the shared light stages. + fn dielectric_hit_one(&mut self) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + self.work.tick(&self.cancel).map_err(error)?; + let optical = self.optical.first_mut().ok_or_else(|| invalid("missing optical task"))?; + let state = optical.pending.as_mut().ok_or_else(|| invalid("missing optical sample"))?; + let pending = self.pending.as_mut().ok_or_else(|| invalid("missing optical hit"))?; + if state.ready { + return Err(invalid("optical hit already consumed")); + } + let hit = pending.hit.ok_or_else(|| invalid("missing captured optical hit"))?; + let look = self.looks.get(hit.primitive_index).ok_or_else(|| invalid("missing optical appearance"))?; + if let Some(input) = self.visibility_owner.options().dielectrics.get(state.selector) { + let index = state.selector; + state.selector += 1; + if input.body_index == look.body_index { + state.selected = Some(index); + state.selector = self.visibility_owner.options().dielectrics.len(); + } + return Ok(()); + } + if state.selector != self.visibility_owner.options().dielectrics.len() { + return Err(invalid("invalid optical selector state")); + } + let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing optical BVH"))?; + let scene = PreparedScene { bvh, primitives: &self.looks, source: self.visibility_owner.source() }; + // Optics always uses the certified geometric boundary, before optional opaque + // shading-normal effects. Distance starts before the numerical spawn offset. + let mut shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; + let exact_face = if optical.nested { + match state.selected.and_then(|index| optical.certificates.get(index).copied().flatten()) { + Some(Certificate::ClosedBox(bounds)) => { + let face = + dielectric::exact_box_face(bounds, shared.vertices, shared.geometric_normal, shared.position, pending.ray).map_err(error)?; + shared.position = face.point; + Some(face) + } + _ => None, + } + } else { + None + }; + if let Some(index) = state.path.medium { + let medium = self.visibility_owner.options().dielectrics.get(index).ok_or_else(|| invalid("active dielectric medium"))?; + let distance = shared.position.dist(state.path.segment_start); + pending.throughput = multiply(pending.throughput, dielectric::attenuation(medium.absorption_per_mm, distance).map_err(error)?); + if !bounded_radiance(pending.throughput) { + return Err(invalid("dielectric throughput exceeds finite bound")); + } + } + state.ready = true; + let Some(index) = state.selected else { + pending.surface_ready = self.effects.is_empty(); + if !pending.surface_ready { + return Ok(()); + } + let mode = self + .visibility_owner + .options() + .reflections + .as_ref() + .and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); + if self.visibility_owner.options().shadows && !self.lights.lights().is_empty() && mode != Some(job::ReflectionMode::Mirror) { + let light = self.lights.lights().first().ok_or_else(|| invalid("missing optical opaque light"))?; + let ray = shared.spawn(light.direction()).map_err(error)?; + if self.visibility_owner.options().directional_shadow_transmission { + begin_directional_shadow(&mut self.visibility_owner, pending, ray, &mut self.work, &self.cancel)?; + } else { + pending.cursor = TraceCursor::new(ray, true); + } + } else { + pending.light = self.lights.lights().len(); + } + return Ok(()); + }; + let medium = self.visibility_owner.options().dielectrics.get(index).ok_or_else(|| invalid("selected dielectric medium"))?; + if medium.body_index != shared.body_index || medium.body_name != shared.body_name { + return Err(invalid("optical captured identity changed")); + } + pending.repeatable_primary = false; + state.path.ray = pending.ray; + state.path.throughput = pending.throughput; + state.path.bounce = pending.bounce; + if let Some(limit) = optical.straight_limit { + // The active transmitted path was popped immediately; a nonzero + // stack or opaque bounce would invalidate the one-segment proof. + // Preserve all real interfaces/Beer/parent checks below. No tint or + // environment shortcut and no expansion of the branching stack. + if state.path.bounce != 0 || state.stack_len != 0 || state.paths != u16::from(state.path.boundaries) + 1 { + return Err(invalid("unexpected branch in certified straight optical transport")); + } + if state.path.boundaries >= limit { + return Err(invalid("certified straight optical crossing bound exceeded")); + } + } else { + if state.path.boundaries == MAX_BOUNDARIES && !optical.deterministic_tir { + // Unchanged legacy policy; strict mode must first + // distinguish a deterministic TIR from another real split. + let radiance = pending.radiance; + return self.finish_transport_path(radiance); + } + if state.path.boundaries > MAX_BOUNDARIES { + return Err(invalid("invalid dielectric boundary depth")); + } + } + let normal = shared.oriented_geometric_normal(); + let direction = state.path.ray.direction(); + let certificate = optical.certificates.get(index).copied().flatten().ok_or_else(|| invalid("missing dielectric certificate"))?; + let (optics, reflected_weight, transmitted_weight, next_medium) = match certificate { + Certificate::ThinSheet => { + if state.path.medium.is_some() { + return Err(invalid("thin sheet inside dielectric medium")); + } + let (optics, reflected, transmitted) = dielectric::thin_sheet(direction, normal, medium).map_err(error)?; + (optics, reflected, transmitted, None) + } + Certificate::ClosedBox(bounds) => { + let boundary_axes = (0..3) + .filter(|axis| { + let p = super::component(shared.position, *axis); + p == super::component(bounds.min(), *axis) || p == super::component(bounds.max(), *axis) + }) + .count(); + if boundary_axes > 1 { + return Err(invalid("dielectric box edge or corner has an ambiguous interface normal")); + } + let parent = optical.parents.get(index).copied().ok_or_else(|| invalid("missing dielectric parent"))?; + let parent_ior = match parent { + Some(parent) => { + self.visibility_owner.options().dielectrics.get(parent).ok_or_else(|| invalid("missing parent optical material"))?.ior + } + None => 1.0, + }; + let (incident, transmitted, next_medium) = if shared.front_face { + if state.path.medium != parent { + return Err(invalid("dielectric entry does not match certified parent")); + } + (parent_ior, medium.ior, Some(index)) + } else { + if state.path.medium != Some(index) { + return Err(invalid("dielectric exit without matching entry")); + } + (medium.ior, parent_ior, parent) + }; + let optics = dielectric::interface(direction, normal, incident, transmitted).map_err(error)?; + let f = optics.reflectance; + let t = (1.0 - f) * (incident / transmitted).powi(2); + (optics, Vec3::new(f, f, f), Vec3::new(t, t, t), next_medium) + } + }; + let spawn = |direction, reflected| match exact_face { + Some(face) => face.spawn(direction, reflected).map_err(error), + None => shared.spawn(direction).map_err(error), + }; + if optical.deterministic_tir && state.path.throughput == Vec3::ZERO { + // Exact zero after real Beer attenuation owes no outgoing ray or + // positive residual; retain all previously accumulated branches. + let radiance = pending.radiance; + return self.finish_transport_path(radiance); + } + if optical.deterministic_tir && optics.transmitted.is_none() { + if optical.straight_limit.is_some() || optics.reflectance != 1.0 || reflected_weight != Vec3::new(1.0, 1.0, 1.0) { + return Err(invalid("strict deterministic TIR disagrees with its interface")); + } + // REAL ray, normal-aware spawn and next traversal, with the same + // already-paid interface tick. Do not push/pop a one-child tree, + // consume branch depth/paths511, clear the shared radiance sum or + // reset ordinary work. The waiting Fresnel branches remain intact. + let path = OpticalPath { + ray: spawn(optics.reflected, true)?, + throughput: dielectric::multiply(state.path.throughput, reflected_weight), + medium: state.path.medium, + segment_start: shared.position, + boundaries: state.path.boundaries, + bounce: pending.bounce, + }; + optical.tir_continuations = optical.tir_continuations.checked_add(1).ok_or_else(|| error(TraceError::WorkLimit))?; + state.path = path; + state.selector = 0; + state.selected = None; + state.ready = false; + // This creates the real new TraceCursor; its following steps pay + // every original BVH/triangle operation and check cancellation. + resume_optical_path(pending, path, self.lights.lights().len())?; + return Ok(()); + } + if optical.deterministic_tir && optical.straight_limit.is_none() && state.path.boundaries == MAX_BOUNDARIES { + return Err(JobError::new(ErrorCode::LimitExceeded, "strict optical non-TIR branch-depth budget exhausted with positive continuation")); + } + let next_depth = state.path.boundaries + 1; + state.push(OpticalPath { + ray: spawn(optics.reflected, true)?, + throughput: dielectric::multiply(state.path.throughput, reflected_weight), + medium: state.path.medium, + segment_start: shared.position, + boundaries: next_depth, + bounce: pending.bounce, + })?; + if let Some(direction) = optics.transmitted { + state.push(OpticalPath { + ray: spawn(direction, false)?, + throughput: dielectric::multiply(state.path.throughput, transmitted_weight), + medium: next_medium, + segment_start: shared.position, + boundaries: next_depth, + bounce: pending.bounce, + })?; + } + let radiance = pending.radiance; + self.finish_transport_path(radiance) + } + + /// Legacy final-only callers keep their exact contract. Progressive callers + /// must consume `step_with_previews`, so no checkpoint is silently discarded. + pub fn step(&mut self, units: usize) -> job::Result { + self.cancel.check()?; + if self.progressive.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU progressive tasks require step_with_previews")); + } + match self.step_with_previews(units)? { + ImagePoll::Pending(progress) => Ok(TaskPoll::Pending(progress)), + ImagePoll::Complete(png) => Ok(TaskPoll::Complete(png)), + ImagePoll::Preview { .. } => Err(invalid("fixed image produced a progressive checkpoint")), + } + } + + fn release_completed_work(&mut self) -> job::Result<()> { + ensure_directional_drained(self.pending.as_ref(), self.lights.lights().len())?; + let bounds = self.visibility_owner.source().bounds; + let old = self.visibility_owner.options(); + let options = RaytraceOptions { + dielectric_transport: old.dielectric_transport, + directional_shadow_transmission: old.directional_shadow_transmission, + budget: old.budget, + progressive: old.progressive, + primary_samples: old.primary_samples, + area_samples: old.area_samples, + seed: old.seed, + preset: old.preset, + exposure_ev: old.exposure_ev, + shadows: old.shadows, + ..Default::default() + }; + self.visibility_owner = dielectric::DirectVisibilityOwner::new(ProductScene { meshes: Vec::new(), bounds }, options); + self.done = true; + self.progressive = None; + self.anisotropic_targets = [None, None]; + self.environment = None; + self.looks = Vec::new(); + self.bvh = None; + self.builder = None; + self.triangles = Vec::new(); + self.pixels = Vec::new(); + self.pending.release(); + self.request.raytrace = None; + self.emissions = Vec::new(); + self.optical = Vec::new(); + self.effects = Vec::new(); + self.lights = Lighting::new(Vec::new()).map_err(error)?; + self.encoder = None; + Ok(()) + } + + pub(crate) fn protected_preview_report(&self) -> Option { + self.work.protected_report() + } + + pub(crate) fn partial_preview_ready(&self, plan: job::PartialPreviewPlan) -> job::Result { + self.cancel.check()?; + plan.validate()?; + if (plan.source_width(), plan.source_height()) != (self.request.width, self.request.height) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview source dimensions changed")); + } + let Some(progressive) = &self.progressive else { return Ok(false) }; + if progressive.partial_plan != Some(plan) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview plan differs from the task policy")); + } + if self.done + || !progressive.film.ready() + || !self.pending.is_none() + || self.optical.first().is_some_and(|o| o.pending.is_some()) + || self.encoder.is_some() + || progressive.partial.is_some() + || progressive.resolving + || !self.pixels.is_empty() + { + return Ok(false); + } + let frontier = progressive.film.partial_frontier()?; + if frontier.completed_passes >= progressive.options.samples_per_pixel { + return Ok(false); + } + let safe = if frontier.updated_prefix == 0 { + frontier.completed_passes > 0 && self.pixel == frontier.pixels + } else { + self.pixel == frontier.updated_prefix + }; + if !safe { + return Ok(false); + } + if self.work.protected.is_some() && !self.work.protected_ready(committed_frontier(frontier)?).map_err(error)? { + return Ok(false); + } + progressive::represented_changed(plan, progressive.last_partial, frontier) + } + + pub(crate) fn completed_pass_preview_ready(&self, plan: job::PartialPreviewPlan) -> job::Result> { + if self.work.protected.is_none() || !self.partial_preview_ready(plan)? { + return Ok(None); + } + let frontier = self.progressive.as_ref().ok_or_else(|| invalid("missing progressive film"))?.film.partial_frontier()?; + Ok((frontier.updated_prefix == 0 && frontier.completed_passes > 0).then_some(frontier.completed_passes)) + } + + /// Host must already hold its one in-flight credit. No host lease or clock + /// lives here; an insufficient optional debit does not mutate trace state. + pub(crate) fn begin_partial_preview(&mut self, plan: job::PartialPreviewPlan) -> job::Result { + if !self.partial_preview_ready(plan)? { + if self.protected_preview_report().is_some_and(|report| report.quota_exhausted) { + return Ok(PartialBegin::Exhausted); + } + return Err(JobError::new(ErrorCode::InvalidRequest, "partial preview requires a fresh safe completed pixel")); + } + let frontier = self.progressive.as_ref().ok_or_else(|| invalid("missing progressive film"))?.film.partial_frontier()?; + if self.work.protected.is_some() { + if !self.work.charge_presentation(committed_frontier(frontier)?, &self.cancel).map_err(error)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected snapshot has no reached unconsumed milestone")); + } + } else { + let units = plan.snapshot_work()?; + if self.work.remaining() < units { + return Ok(PartialBegin::Exhausted); + } + self.work.charge(units, &self.cancel).map_err(error)?; + } + let count = usize::try_from(plan.pixels()).map_err(|_| error(TraceError::MemoryLimit))?; + let mut covered = Vec::new(); + covered.try_reserve_exact(count).map_err(|_| error(TraceError::AllocationFailed))?; + if covered.capacity() != count { + return Err(error(TraceError::MemoryLimit)); + } + self.cancel.check()?; + let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing progressive film"))?; + progressive.partial = Some(progressive::PartialResolve { plan, frontier, resume_pixel: self.pixel, next: 0, covered }); + Ok(PartialBegin::Started) + } + + /// One prepaid representative resolve, encoder setup, or encoding row. + /// Work was debited before allocation; cancel/continuation bounds remain real. + fn partial_preview_one(&mut self) -> job::Result> { + self.cancel.check()?; + let (plan, frontier, resume_pixel, next) = { + let partial = self.progressive.as_ref().and_then(|p| p.partial.as_ref()).ok_or_else(|| invalid("missing partial resolve state"))?; + (partial.plan, partial.frontier, partial.resume_pixel, partial.next) + }; + let count = usize::try_from(plan.pixels()).map_err(|_| error(TraceError::MemoryLimit))?; + if next < count { + let index = plan.source_index(next)?; + let value = self.progressive.as_ref().ok_or_else(|| invalid("missing partial film"))?.film.partial_pixel(index)?; + let (rgba, covered) = match value { + crate::film::primary::PartialPixel::Unknown => ([0; 4], 0), + crate::film::primary::PartialPixel::Sampled { linear_premultiplied, covered, count } => { + let [r, g, b] = linear_premultiplied; + ( + composite_spatial(Vec3::new(r, g, b), covered, count, self.request.background, self.visibility_owner.options().exposure_ev)?, + covered, + ) + } + }; + if next.checked_mul(4) != Some(self.pixels.len()) { + return Err(invalid("partial RGBA cursor mismatch")); + } + self.cancel.check()?; + let partial = self.progressive.as_mut().and_then(|p| p.partial.as_mut()).ok_or_else(|| invalid("missing partial cell state"))?; + if partial.covered.len() != next || partial.covered.capacity() != count { + return Err(invalid("partial coverage cursor or capacity mismatch")); + } + self.pixels.extend_from_slice(&rgba); + partial.covered.push(covered); + partial.next += 1; + return Ok(None); + } + if next != count { + return Err(invalid("partial display cursor exceeded its plan")); + } + if self.encoder.is_none() { + let limit = plan.encoded_limit()?; + let capacity = usize::try_from(limit).map_err(|_| error(TraceError::MemoryLimit))?; + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(|_| error(TraceError::AllocationFailed))?; + if output.capacity() != capacity { + return Err(error(TraceError::MemoryLimit)); + } + self.cancel.check()?; + self.encoder = Some(job::encoding::PngEncoding::with_output(plan.width(), plan.height(), limit, self.cancel.clone(), output)?); + return Ok(None); + } + let png = self.encoder.as_mut().ok_or_else(|| invalid("missing partial encoder"))?.step(&self.pixels)?; + let Some(png) = png else { return Ok(None) }; + self.cancel.check()?; + let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing completed partial film"))?; + if progressive.film.partial_frontier()? != frontier || self.pixel != resume_pixel || !self.pending.is_none() { + return Err(invalid("partial snapshot changed its captured sample frontier")); + } + let partial = progressive.partial.take().ok_or_else(|| invalid("missing completed partial output"))?; + if partial.covered.len() != count || partial.covered.capacity() != count { + return Err(invalid("partial covered output differs from its plan")); + } + let updated_prefix = u64::try_from(frontier.updated_prefix).map_err(|_| error(TraceError::MemoryLimit))?; + progressive.last_partial = Some(frontier); + self.encoder = None; + self.pixels.clear(); + // Preserve the complete-pass sentinel too: after host hashing, the + // ordinary continuation must still charge its tick before P -> 0. + self.pixel = resume_pixel; + Ok(Some(ImageAdvance::Partial { png, covered: partial.covered, completed_passes: frontier.completed_passes, updated_prefix })) + } + + pub(crate) fn step_with_partial_previews(&mut self, units: usize) -> job::Result { + if self.progressive.as_ref().is_none_or(|p| p.partial_plan.is_none()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial polling requires the CPU partial policy")); + } + match self.advance_image(units)? { + ImageAdvance::Legacy(ImagePoll::Pending(progress)) => Ok(PartialImagePoll::Pending(progress)), + ImageAdvance::Legacy(ImagePoll::Complete(png)) => Ok(PartialImagePoll::Complete(png)), + ImageAdvance::Partial { png, covered, completed_passes, updated_prefix } => { + Ok(PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix }) + } + ImageAdvance::Legacy(ImagePoll::Preview { .. }) => Err(invalid("partial policy produced a legacy checkpoint")), + } + } + + fn resolve_progressive_one(&mut self) -> job::Result<()> { + self.work.tick(&self.cancel).map_err(error)?; + let progressive = self.progressive.as_mut().ok_or_else(|| invalid("missing progressive resolve state"))?; + let count = self.request.width as usize * self.request.height as usize; + if progressive.resolve_pixel < count { + let (rgb, covered, samples) = progressive.film.pixel(progressive.resolve_pixel)?; + let rgba = composite_spatial( + Vec3::new(rgb[0], rgb[1], rgb[2]), + covered, + samples, + self.request.background, + self.visibility_owner.options().exposure_ev, + )?; + self.cancel.check()?; + self.pixels.extend_from_slice(&rgba); + progressive.resolve_pixel += 1; + } else { + let capacity = usize::try_from(self.admission.encoded_limit).map_err(|_| error(TraceError::MemoryLimit))?; + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(|_| error(TraceError::AllocationFailed))?; + if output.capacity() != capacity { + return Err(error(TraceError::MemoryLimit)); + } + self.cancel.check()?; + self.encoder = Some(job::encoding::PngEncoding::with_output( + self.request.width, + self.request.height, + self.admission.encoded_limit, + self.cancel.clone(), + output, + )?); + } + Ok(()) + } + + /// At most four continuations/encoding rows. One cumulative work budget spans + /// geometry preparation, every absolute camera sample and every checkpoint. + pub fn step_with_previews(&mut self, units: usize) -> job::Result { + if self.progressive.as_ref().is_some_and(|p| p.partial_plan.is_some()) { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial CPU tasks require their additive internal poll")); + } + match self.advance_image(units)? { + ImageAdvance::Legacy(poll) => Ok(poll), + ImageAdvance::Partial { .. } => Err(invalid("legacy policy produced a partial snapshot")), + } + } + + fn advance_image(&mut self, units: usize) -> job::Result { + self.cancel.check()?; + if units == 0 || units > 16384 || self.done { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid raytrace step or completed task")); + } + for _ in 0..units.min(4) { + if self.progressive.as_ref().is_some_and(|p| p.partial.is_some()) { + if let Some(preview) = self.partial_preview_one()? { + return Ok(preview); + } + } else if self.progressive.as_ref().is_some_and(|p| !p.film.ready()) { + self.progressive + .as_mut() + .ok_or_else(|| invalid("missing progressive initialization"))? + .film + .initialize_one(&self.cancel, &mut || self.work.tick(&self.cancel).map_err(error))?; + } else if let Some(encoder) = &mut self.encoder { + if self.progressive.is_some() { + self.work + .charge(if encoder.row() < self.request.height as usize { u64::from(self.request.width) } else { 1 }, &self.cancel) + .map_err(error)?; + } + if let Some(png) = encoder.step(&self.pixels)? { + self.cancel.check()?; + if let Some(progressive) = &mut self.progressive { + // The host hashes these exact bytes incrementally. Debit + // their full scan here, before handing ownership over. + self.work.charge(png.len() as u64, &self.cancel).map_err(error)?; + let samples_per_pixel = progressive.film.samples(); + if samples_per_pixel < progressive.options.samples_per_pixel { + progressive.resolving = false; + progressive.resolve_pixel = 0; + self.encoder = None; + self.pixels.clear(); + self.pixel = 0; + return Ok(ImageAdvance::Legacy(ImagePoll::Preview { png, samples_per_pixel })); + } + } + self.release_completed_work()?; + return Ok(ImageAdvance::Legacy(ImagePoll::Complete(png))); + } + } else if self.progressive.as_ref().is_some_and(|p| p.resolving) { + self.resolve_progressive_one()?; + } else if self.environment.as_ref().is_some_and(|e| !e.ready()) { + self.work.tick(&self.cancel).map_err(error)?; + self.environment + .as_mut() + .ok_or_else(|| invalid("missing environment preparation"))? + .prepare_one(|| self.cancel.is_cancelled()) + .map_err(environment_error)?; + } else if self.bvh.is_some() { + if self.pixel == self.request.width as usize * self.request.height as usize { + if let Some(progressive) = &mut self.progressive { + let samples = progressive.film.samples(); + if self.request.cpu_progressive_every_pass && progressive.partial_plan.is_some() && samples < progressive.options.samples_per_pixel && samples > self.last_pass_boundary + { + self.last_pass_boundary = samples; + return Ok(ImageAdvance::Legacy(ImagePoll::Pending(self.progress()))); + } + self.work.tick(&self.cancel).map_err(error)?; + if samples == progressive.options.samples_per_pixel || (progressive.partial_plan.is_none() && (self.request.cpu_progressive_every_pass || samples.is_power_of_two())) { + progressive.resolving = true; + } else { + self.pixel = 0; + } + } else { + self.encoder = Some(job::encoding::PngEncoding::new( + self.request.width, + self.request.height, + self.admission.encoded_limit, + self.cancel.clone(), + )?); + } + } else { + self.pixel_one()?; + } + } else if let Some(builder) = &mut self.builder { + let progress = builder.step(1, &self.cancel).map_err(error)?; + for _ in self.build_used..progress.work_used { + self.work.tick(&self.cancel).map_err(error)?; + } + self.build_used = progress.work_used; + if progress.complete { + self.bvh = Some(self.builder.take().ok_or_else(|| invalid("missing builder"))?.finish().map_err(error)?); + } + } else { + self.prepare_one()?; + } + } + Ok(ImageAdvance::Legacy(ImagePoll::Pending(self.progress()))) + } +} +/// Apply the already selected deterministic effect to the shared opaque hit. +/// The captured geometric normal, ray origin, visibility and topology are unchanged. +fn resolved_surface_hit<'a>( + scene: &PreparedScene<'a>, + pending: &PendingPixel, + effects: &[(usize, crate::surface_patterns::PreparedEffect)], +) -> job::Result> { + if !pending.surface_ready || pending.surface_cursor != effects.len() { + return Err(invalid("surface effect is not completely resolved")); + } + let mut shared = scene.resolve_hit(pending.ray, pending.hit.ok_or_else(|| invalid("missing prepared surface hit"))?).map_err(error)?; + if let Some(index) = pending.surface_index { + let (body_index, effect) = effects.get(index).ok_or_else(|| invalid("missing selected surface effect"))?; + if *body_index != shared.body_index { + return Err(invalid("selected surface effect belongs to another body")); + } + let changed = effect.apply(shared.surface, shared.shading_normal, shared.oriented_geometric_normal(), shared.position)?; + shared.surface = changed.surface; + shared.shading_normal = changed.shading_normal; + } + Ok(shared) +} + +fn bounded_radiance(v: Vec3) -> bool { + v.is_finite() && [v.x, v.y, v.z].into_iter().all(|c| (0.0..=1e12).contains(&c)) +} +fn primary_offset(samples: u8, ordinal: u8) -> job::Result<[f64; 2]> { + let side = match samples { + 1 => 1, + 4 => 2, + 16 => 4, + _ => return Err(invalid("invalid spatial sample count")), + }; + if ordinal >= samples { + return Err(invalid("invalid spatial sample ordinal")); + } + Ok([(f64::from(ordinal % side) + 0.5) / f64::from(side), (f64::from(ordinal / side) + 0.5) / f64::from(side)]) +} +fn spatial_key(pixel: u64, ordinal: u8, samples: u8) -> job::Result { + primary_offset(samples, ordinal)?; + pixel + .checked_mul(u64::from(samples)) + .and_then(|n| n.checked_add(u64::from(ordinal))) + .map(|n| n ^ 0x4141_5052_494d_4152) + .ok_or_else(|| invalid("spatial seed overflow")) +} +/// Distinguish film and spatial ordinals before sampling an emitter. The legacy +/// single-primary first pass keeps its original key and reference image bytes. +fn area_sample_key(pixel: u64, spatial: u8, spatial_samples: u8, film_sample: u32) -> job::Result { + primary_offset(spatial_samples, spatial)?; + if film_sample >= job::MAX_CPU_SAMPLES_PER_PIXEL { + return Err(invalid("area-light film sample ordinal exceeds the admitted cap")); + } + if spatial_samples == 1 && film_sample == 0 { + return Ok(pixel); + } + if film_sample < 4096 { + // Preserve every historical ordinal and fixed-primary key exactly. + return pixel + .checked_mul(4096 * 16) + .and_then(|key| key.checked_add(u64::from(film_sample) * 16 + u64::from(spatial))) + .map(|key| key ^ 0x4152_4541_5341_4d50) + .ok_or_else(|| invalid("area-light sample identity overflow")); + } + if pixel >= (1_u64 << 26) || film_sample >= (1_u32 << 20) { + return Err(invalid("area-light extended sample identity exceeds its fields")); + } + let mode = match spatial_samples { + 1 => 0_u64, + 4 => 1, + 16 => 2, + _ => return Err(invalid("area-light primary mode")), + }; + // Separate extended ordinals from old keys and reserve ten low bits for + // the existing light/emitter RNG offsets. No target/budget/cadence key. + Ok((1_u64 << 63) | (pixel << 36) | (u64::from(film_sample) << 16) | (mode << 14) | (u64::from(spatial) << 10)) +} + +fn composite_spatial(premultiplied: Vec3, covered: u32, attempts: u32, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { + if attempts == 0 || attempts > job::MAX_CPU_SAMPLES_PER_PIXEL || covered > attempts || !bounded_radiance(premultiplied) { + return Err(invalid("invalid spatial coverage/radiance")); + } + if covered == 0 { + if premultiplied != Vec3::ZERO { + return Err(invalid("uncovered spatial radiance")); + } + return Ok([background[0], background[1], background[2], 255]); + } + let coverage = f64::from(covered) / f64::from(attempts); + let geometry = map_to_display(premultiplied / coverage, exposure).map_err(error)?; + let display = if covered == attempts { + geometry + } else { + let bg = Vec3::new(srgb8_to_linear(background[0]), srgb8_to_linear(background[1]), srgb8_to_linear(background[2])); + geometry * coverage + bg * (1.0 - coverage) + }; + Ok([encode8(display.x), encode8(display.y), encode8(display.z), 255]) +} + +/// One sample preparation, one traversal operation OR one visible-sum operation. +/// Reuses the existing primary/directional cursor: no second task or heap state. +fn punctual_one( + pending: &mut PendingPixel, + options: &RaytraceOptions, + bvh: &Bvh, + context: (super::prepared::SharedHit<'_>, Option, Option), + work: &mut WorkBudget, + cancel: &CancelToken, + diagnostics: &mut job::PunctualDiagnostics, +) -> job::Result<()> { + let (shared, target, mode) = context; + if pending.punctual_shadow { + if let Some(blocker) = pending.cursor.step(bvh, work, cancel).map_err(error)? { + if blocker.is_some() { + pending.punctual_value = Vec3::ZERO; + } + pending.punctual_shadow = false; + pending.punctual_ready = true; + } + return Ok(()); + } + work.tick(cancel).map_err(error)?; + if pending.punctual_ready { + add_punctual_radiance(pending, pending.punctual_value, diagnostics); + pending.punctual_index += 1; + pending.punctual_ready = false; + return Ok(()); + } + let inputs = options.punctual_lights.as_ref().ok_or_else(|| invalid("punctual options missing"))?; + if mode == Some(job::ReflectionMode::Mirror) { + pending.punctual_index = inputs.len(); + return Ok(()); + } + let light = inputs.get(pending.punctual_index).copied().ok_or_else(|| invalid("punctual source index"))?.light().map_err(error)?; + let sample = light.sample(shared.position).map_err(error)?; + if let Some(reason) = sample.omitted { + match reason { + super::punctual::OmittedSample::NearSource => diagnostics.near_source = diagnostics.near_source.saturating_add(1), + super::punctual::OmittedSample::RadianceLimit => diagnostics.radiance_limit = diagnostics.radiance_limit.saturating_add(1), + } + pending.punctual_index += 1; + return Ok(()); + } + let geometric = shared.oriented_geometric_normal(); + let cosine = if target.is_some() { geometric } else { shared.shading_normal }.dot(sample.direction).max(0.0); + let contribution = if geometric.dot(sample.direction) <= 0.0 || cosine == 0.0 || sample.incident_linear_srgb == Vec3::ZERO { + Vec3::ZERO + } else { + let view = -pending.ray.direction(); + let f = if let Some(target) = target { + target.direct_brdf(shared.surface, geometric, view, sample.direction).map_err(error)? + } else { + shared.surface.brdf(shared.shading_normal, view, sample.direction).map_err(|_| invalid("punctual opaque response"))? + }; + multiply(f, sample.incident_linear_srgb) * cosine + }; + if super::lighting::validate_radiance(contribution).is_err() { + diagnostics.radiance_limit = diagnostics.radiance_limit.saturating_add(1); + pending.punctual_index += 1; + return Ok(()); + } + pending.punctual_value = contribution; + if options.shadows && contribution != Vec3::ZERO { + let Some(ray) = sample.shadow_ray(shared).map_err(error)? else { + diagnostics.shadow_offset_crossed = diagnostics.shadow_offset_crossed.saturating_add(1); + pending.punctual_index += 1; + return Ok(()); + }; + pending.cursor = TraceCursor::new(ray, true); + pending.punctual_shadow = true; + } else { + add_punctual_radiance(pending, contribution, diagnostics); + pending.punctual_index += 1; + } + Ok(()) +} + +fn add_punctual_radiance(pending: &mut PendingPixel, contribution: Vec3, diagnostics: &mut job::PunctualDiagnostics) { + let candidate = pending.radiance + multiply(pending.throughput, contribution); + if super::lighting::validate_radiance(candidate).is_ok() { + pending.radiance = candidate; + } else { + diagnostics.radiance_limit = diagnostics.radiance_limit.saturating_add(1); + } +} + +fn multiply(a: Vec3, b: Vec3) -> Vec3 { + Vec3::new(a.x * b.x, a.y * b.y, a.z * b.z) +} +#[cfg(test)] +fn shadow_ray(ray: Ray, hit: super::Hit, light: Vec3, vertices: [Vec3; 3]) -> super::Result { + let mut n = hit.geometry.geometric_normal; + if n.dot(light) < 0.0 { + n = -n; + } + let [a, b, c] = hit.geometry.barycentric; + let [va, vb, vc] = vertices; + // Reconstruct from captured vertices, not a distant camera. Component-wise + // rounding bounds avoid an unrelated large X translation displacing a Z plane. + let p = va * a + vb * b + vc * c; + let magnitude = |x: f64, y: f64, z: f64| x.abs() * a.abs() + y.abs() * b.abs() + z.abs() * c.abs(); + let e = Vec3::new(magnitude(va.x, vb.x, vc.x), magnitude(va.y, vb.y, vc.y), magnitude(va.z, vb.z, vc.z)) * (8.0 * f64::EPSILON); + let distance = n.x.abs() * e.x + n.y.abs() * e.y + n.z.abs() * e.z; + let shifted = p + n * distance; + let outward = |v: f64, n: f64| { + if n > 0.0 { + v.next_up() + } else if n < 0.0 { + v.next_down() + } else { + v + } + }; + let _ = ray; // hit position comes from geometry, independent of camera distance. + Ray::new(Vec3::new(outward(shifted.x, n.x), outward(shifted.y, n.y), outward(shifted.z, n.z)), light, 0.0_f64.next_up(), super::MAX_DISTANCE_MM) +} + +fn primary_ray(request: &ImageRequest, x: f64, y: f64, clip: (f64, f64)) -> super::Result { + let camera = &request.camera; + let (mut origin, direction) = camera.ray(x, y, request.width as f64, request.height as f64); + if camera.fov == 0.0 { + origin -= camera.back() * (camera.distance * 3.0); + } + let forward = -camera.back(); + let cosine = direction.dot(forward); + if !cosine.is_finite() || cosine <= 0.0 { + return Err(TraceError::InvalidInput("camera ray direction")); + } + let depth = (origin - camera.eye()).dot(forward); + let start = (clip.0 - depth) / cosine; + let length = (clip.1 - clip.0) / cosine; + Ray::new(origin + direction * start, direction, 0.0, length) +} + +#[cfg(test)] +#[path = "image_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "deterministic_primary_tests.rs"] +mod deterministic_primary_tests; + +#[cfg(test)] +#[path = "reflection_image_tests.rs"] +mod reflection_tests; + +fn environment_error(e: crate::lighting::HdrError) -> JobError { + use crate::lighting::HdrErrorCode; + let code = match e.code { + HdrErrorCode::Cancelled => ErrorCode::Cancelled, + HdrErrorCode::LimitExceeded => ErrorCode::LimitExceeded, + HdrErrorCode::AllocationFailed => ErrorCode::AllocationFailed, + _ => ErrorCode::InvalidRequest, + }; + JobError::new(code, e.to_string()) +} + +#[cfg(test)] +#[path = "primary_aa_tests.rs"] +mod primary_aa_tests; + +// One bounded continuation operation, using the same cursor, work accumulator and task. +fn area_one( + pending: &mut PendingPixel, + options: &RaytraceOptions, + bvh: &Bvh, + context: (super::prepared::SharedHit<'_>, Option, Option), + work: &mut WorkBudget, + cancel: &CancelToken, + pixel: u64, +) -> job::Result<()> { + let (shared, target, mode) = context; + if pending.area_shadow { + if let Some(blocker) = pending.cursor.step(bvh, work, cancel).map_err(error)? { + if blocker.is_some() { + pending.area_value = Vec3::ZERO; + } + pending.area_shadow = false; + pending.area_ready = true; + } + return Ok(()); + } + work.tick(cancel).map_err(error)?; + if pending.area_ready { + pending.radiance += multiply(pending.throughput, pending.area_value); + super::lighting::validate_radiance(pending.radiance).map_err(error)?; + pending.area_index += 1; + pending.area_ready = false; + return Ok(()); + } + let inputs = options.area_lights.as_ref().ok_or_else(|| invalid("area options missing"))?; + if mode == Some(job::ReflectionMode::Mirror) { + pending.area_light = inputs.len(); + return Ok(()); + } + let count = options.area_samples.unwrap_or(16); + if pending.area_index == count { + pending.area_light += 1; + pending.area_index = 0; + return Ok(()); + } + let input = inputs.get(pending.area_light).ok_or_else(|| invalid("area source index"))?; + let vec = |[x, y, z]: [f64; 3]| Vec3::new(x, y, z); + let light = super::area::RectangleLight::new(vec(input.center_mm), vec(input.edge_u_mm), vec(input.edge_v_mm), vec(input.color), input.intensity) + .map_err(error)?; + let Some(sample) = + light.sample(shared.position, pixel, pending.area_light as u32, pending.area_index, count, options.seed.unwrap_or(0)).map_err(error)? + else { + pending.area_index += 1; + return Ok(()); + }; + let geometric = shared.oriented_geometric_normal(); + let cosine = if target.is_some() { geometric } else { shared.shading_normal }.dot(sample.direction()).max(0.0); + let contribution = if geometric.dot(sample.direction()) <= 0.0 || cosine == 0.0 { + Vec3::ZERO + } else { + let view = -pending.ray.direction(); + let f = if let Some(target) = target { + target.direct_brdf(shared.surface, geometric, view, sample.direction()).map_err(error)? + } else { + shared.surface.brdf(shared.shading_normal, view, sample.direction()).map_err(|_| invalid("area opaque response"))? + }; + multiply(f, sample.incident()) * cosine + }; + super::lighting::validate_radiance(contribution).map_err(error)?; + pending.area_value = contribution; + if options.shadows && contribution != Vec3::ZERO { + let origin = shared.spawn(sample.direction()).map_err(error)?.origin(); + pending.cursor = TraceCursor::new(sample.shadow_ray(origin).map_err(error)?, true); + pending.area_shadow = true; + } else { + pending.radiance += multiply(pending.throughput, contribution); + super::lighting::validate_radiance(pending.radiance).map_err(error)?; + pending.area_index += 1; + } + Ok(()) +} + +#[cfg(test)] +#[path = "punctual_image_tests.rs"] +mod punctual_image_tests; diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/image_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/image_tests.rs new file mode 100644 index 000000000..61972ce4a --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/image_tests.rs @@ -0,0 +1,3581 @@ +use super::*; +use solidcraft_geom::Aabb3; +fn emission_fixture(reverse: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + use std::sync::Arc; + let mut meshes = Vec::new(); + for (name, lo, hi) in [("emitter", -20.0, 0.0), ("receiver", 0.0, 20.0)] { + let mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(lo, -10.0, 0.0), Vec3::new(hi, -10.0, 0.0), Vec3::new(hi, 10.0, 0.0), Vec3::new(lo, 10.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: if reverse { vec![[0, 2, 1], [0, 3, 2]] } else { vec![[0, 1, 2], [0, 2, 3]] }, + tri_face: vec![0; 2], + ..Default::default() + }; + meshes.push(crate::ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let mut request = request(); + request.width = 2; + request.height = 1; + request.camera.distance = 25.0; + request.camera.fov = 0.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + emissions: Some(vec![job::SurfaceEmission { + body_index: 0, + body: "emitter".into(), + color: [0.25, 0.5, 1.0], + strength: 1.0, + sides: job::EmissionSides::Front, + }]), + ..Default::default() + }; + (ProductScene { meshes, bounds }, request, options) +} +fn emission_png(scene: ProductScene, mut request: ImageRequest, options: RaytraceOptions) -> Vec { + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..10_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("emission fixture did not complete"); +} +#[test] +fn emission_actual_png_adds_linear_radiance_once_and_never_lights_neighbor() { + let (scene, request, mut options) = emission_fixture(false); + for ev in [0.0, 1.0] { + options.exposure_ev = ev; + let image = ::image::load_from_memory(&emission_png(scene.clone(), request.clone(), options.clone())).unwrap().to_rgba8(); + let expected = [0.25, 0.5, 1.0].map(|c| { + let v = c * 2.0_f64.powf(ev); + encode8(v / (1.0 + v)) + }); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); + assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255]); + } +} +#[test] +fn emission_zero_default_png_equivalence_and_geometric_sidedness() { + let (scene, request, mut options) = emission_fixture(false); + options.emissions.as_mut().unwrap()[0].strength = 0.0; + let zero = emission_png(scene.clone(), request.clone(), options.clone()); + options.emissions = None; + assert_eq!(zero, emission_png(scene, request, options)); + let (scene, request, mut options) = emission_fixture(true); + let image = ::image::load_from_memory(&emission_png(scene.clone(), request.clone(), options.clone())).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [0, 0, 0, 255], "shading normals cannot turn a back face into an emitter"); + options.emissions.as_mut().unwrap()[0].sides = job::EmissionSides::Both; + let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8(); + assert!(image.get_pixel(0, 0).0[0] > 0); +} +#[test] +fn emission_stale_duplicate_and_capacity_targets_refuse_before_work() { + let (scene, mut request, mut options) = emission_fixture(false); + options.emissions.as_mut().unwrap()[0].body = "renamed".into(); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidScene); + let (_, _, mut options) = emission_fixture(false); + let first = options.emissions.as_ref().unwrap()[0].clone(); + options.emissions.as_mut().unwrap().push(first); + assert!(options.validate().is_err()); + options.emissions = Some(Vec::with_capacity(64)); + assert!(options.validate().is_err()); +} +#[test] +fn emission_survives_face_reflectance_override_without_changing_captured_geometry() { + let (mut scene, request, options) = emission_fixture(false); + let original = scene.meshes[0].mesh.clone(); + let baseline = emission_png(scene.clone(), request.clone(), options.clone()); + scene.meshes[0].faces.push(crate::FaceAppearance { transmission: None, face: 0, color: [0; 3], opacity: 1.0, surface: None }); + assert_eq!(baseline, emission_png(scene.clone(), request, options)); + assert!(std::sync::Arc::ptr_eq(&original, &scene.meshes[0].mesh)); + assert_eq!(scene.meshes[0].faces[0].color, [0; 3]); +} +#[test] +fn emission_scan_observes_cancel_and_exhausts_shared_work_without_png() { + let (scene, mut request, options) = emission_fixture(false); + request.raytrace = Some(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene, request, cancel.clone(), options).unwrap(); + for _ in 0..10_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light == task.lights.lights().len() && p.emission_cursor == 0) { + task.work.limit = task.work.used() + 1; + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + assert!(!task.done); + assert!(task.pixels.is_empty()); + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + return; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + panic!("fixture never reached shading"); +} +#[test] +fn thirty_two_emission_bindings_resume_with_four_work_units_and_cancel_without_publication() { + for cancel_midway in [false, true] { + let (mut scene, mut request, mut options) = emission_fixture(false); + while scene.meshes.len() < 32 { + let mut mesh = scene.meshes[1].clone(); + mesh.name = format!("receiver {}", scene.meshes.len()); + scene.meshes.push(mesh); + } + let base = options.emissions.as_ref().unwrap()[0].clone(); + let mut values = Vec::with_capacity(32); + for index in (1..32).chain(std::iter::once(0)) { + values.push(job::SurfaceEmission { body_index: index, body: scene.meshes[index].name.clone(), ..base.clone() }); + } + options.emissions = Some(values); + request.raytrace = Some(options.clone()); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene, request, cancel.clone(), options).unwrap(); + for _ in 0..100_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light == task.lights.lights().len() && p.emission_cursor == 0) { + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert_eq!(task.pending.as_ref().unwrap().emission_cursor, 0); + assert_eq!(task.pending.as_ref().unwrap().radiance, Vec3::ZERO); + for expected_cursor in (4..=32).step_by(4) { + let before = task.work.used(); + assert!(matches!(task.step(16384).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 4); + let pending = task.pending.as_ref().unwrap(); + assert_eq!(pending.emission_cursor, expected_cursor); + assert_eq!(pending.radiance, if expected_cursor == 32 { Vec3::new(0.25, 0.5, 1.0) } else { Vec3::ZERO }); + assert!(task.pixels.is_empty()); + if cancel_midway && expected_cursor == 16 { + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used() - before, 4); + assert!(task.pixels.is_empty()); + break; + } + } + if !cancel_midway { + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 1); + assert_eq!(task.pixel, 1); + assert_eq!(task.pixels, [encode8(0.25 / 1.25), encode8(0.5 / 1.5), encode8(0.5), 255]); + } + } +} +fn request() -> ImageRequest { + ImageRequest { + cpu_progressive_every_pass: true, + 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: None, + camera: Default::default(), + width: 8, + height: 8, + background: [10, 20, 30], + transparent_background: false, + } +} +#[test] +fn image_work_exhaustion_is_typed_and_never_publishes_partial_png() { + let mut task = + ImageTask::new(ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }, request(), CancelToken::default(), Default::default()).unwrap(); + task.work = WorkBudget::new(2).unwrap(); + let mut previous = 0; + for _ in 0..20 { + match task.step(1) { + Ok(TaskPoll::Pending(_)) => { + assert!(task.work.used() >= previous); + previous = task.work.used(); + } + Ok(TaskPoll::Complete(_)) => panic!("exhausted task published a frame"), + Err(e) => { + assert_eq!(e.code, ErrorCode::LimitExceeded); + assert_eq!(task.work.used(), 2); + return; + } + } + } + panic!("tiny budget did not stop image"); +} +#[test] +fn thin_shadow_occluder_survives_large_unrelated_translation() { + for x in [0.0, 1.0e12 - 100.0] { + let vertices = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 20.0, 0.0, 0.0), Vec3::new(x, 20.0, 0.0)]; + let receiver = Triangle::new(vertices).unwrap(); + let primary = Ray::new(Vec3::new(x + 5.0, 5.0, 10.0), -Vec3::Z, 0.0, 20.0).unwrap(); + let geometry = receiver.intersect(&primary).unwrap(); + let shadow = shadow_ray(primary, super::super::Hit { primitive_index: 0, geometry }, Vec3::Z, vertices).unwrap(); + assert!(shadow.interval()[0] > 0.0, "secondary rays exclude signed-zero distance after underflow"); + assert!(receiver.intersect(&shadow).is_none(), "self-shadow at translation {x}"); + let occluder = Triangle::new(vertices.map(|v| v + Vec3::Z * 0.005)).unwrap(); + assert!(occluder.intersect(&shadow).is_some(), "thin blocker was skipped at translation {x}"); + } +} +#[test] +fn primary_intervals_follow_camera_clip_planes_for_both_projections_and_up_axes() { + for fov in [0.0, 0.7] { + for up in [crate::UpAxis::Z, crate::UpAxis::Y] { + let mut request = request(); + request.camera.fov = fov; + request.camera.up = up; + let clip = request.camera.clip(20.0); + let ray = primary_ray(&request, 4.0, 4.0, clip).unwrap(); + let forward = -request.camera.back(); + let near_depth = (ray.origin() - request.camera.eye()).dot(forward); + let far_depth = (ray.at(ray.interval()[1]).unwrap() - request.camera.eye()).dot(forward); + assert!((near_depth - clip.0).abs() < 1e-9); + assert!((far_depth - clip.1).abs() < 1e-9); + } + } +} +#[test] +fn resumable_cursor_matches_original_visibility_and_charges_each_unit() { + let cancel = CancelToken::default(); + let triangle = Triangle::new([Vec3::ZERO, Vec3::X, Vec3::Y]).unwrap(); + let mut builder = BvhBuilder::new(vec![triangle], limits(job::CpuBudget::Compact), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let ray = Ray::new(Vec3::new(0.2, 0.2, 1.0), -Vec3::Z, 0.0, 2.0).unwrap(); + let expected = bvh.closest_hit(&ray, &mut WorkBudget::new(100).unwrap(), &cancel).unwrap(); + let mut cursor = TraceCursor::new(ray, false); + let mut work = WorkBudget::new(100).unwrap(); + for _ in 0..100 { + let before = work.used(); + let result = cursor.step(&bvh, &mut work, &cancel).unwrap(); + assert_eq!(work.used(), before + 1); + if let Some(actual) = result { + assert_eq!(actual, expected); + return; + } + } + panic!("cursor failed to finish"); +} +#[test] +fn actual_png_has_analytic_lit_and_cast_shadow_pixels() { + use crate::ProductMesh; + use solidcraft_geom::Mesh; + use std::sync::Arc; + fn plane(z: f64, x0: f64, x1: f64) -> ProductMesh { + let mesh = Mesh { + positions: vec![Vec3::new(x0, -10.0, z), Vec3::new(x1, -10.0, z), Vec3::new(x1, 10.0, z), Vec3::new(x0, 10.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }; + ProductMesh { + transmission: None, + name: format!("plane {z}"), + mesh: Arc::new(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(), + } + } + let meshes = vec![plane(0.0, -20.0, 20.0), plane(5.0, -5.0, 5.0)]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let scene = ProductScene { meshes, bounds }; + let mut request = request(); + request.width = 40; + request.height = 40; + request.camera.distance = 50.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(vec![job::DirectionalLightOptions { direction: [-1.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]), + ..Default::default() + }; + fn render(scene: ProductScene, mut request: ImageRequest, options: RaytraceOptions) -> ::image::RgbaImage { + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return ::image::load_from_memory(&png).unwrap().to_rgba8(); + } + } + panic!("small analytic render did not complete"); + } + let shadowed = render(scene.clone(), request.clone(), options.clone()); + let lit = render(scene, request, RaytraceOptions { shadows: false, ..options }); + // Top view: screen x maps world x, width40 spans[-20,20]. Blocker[-5,5] + // at z5 casts a footprint[0,10] for the light toward(-1,0,+1). + let shadow = shadowed.get_pixel(27, 20).0; + let unshadowed = lit.get_pixel(27, 20).0; + assert_eq!(shadow, [0, 0, 0, 255]); + // White fully rough conductor: F=1, D=1/pi, Smith visibility + // at normal view yields BRDF=1/[2*pi*(1+cosL)]. + let cosine = (0.5_f64).sqrt(); + let radiance = cosine / (2.0 * std::f64::consts::PI * (1.0 + cosine)); + let expected = encode8(radiance / (1.0 + radiance)); + assert_eq!(unshadowed, [expected, expected, expected, 255]); + assert_eq!(shadowed.get_pixel(7, 20), lit.get_pixel(7, 20), "unoccluded receiver changes when toggling shadows"); +} +fn triangle_task(cancel: CancelToken) -> ImageTask { + use std::sync::Arc; + let mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(0.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "work fixture".into(), + mesh: Arc::new(mesh), + color: [220; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let mut request = request(); + request.camera.distance = 50.0; + request.camera.set_view(crate::StandardView::Top); + ImageTask::new(scene, request, cancel, Default::default()).unwrap() +} +#[test] +fn build_primary_and_shadows_share_cumulative_work_and_exhaust_atomically() { + let mut task = triangle_task(CancelToken::default()); + let mut previous = 0; + let mut built = false; + for _ in 0..10_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() >= previous); + previous = task.work.used(); + built |= task.builder.is_some(); + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && p.light < task.lights.lights().len()) { + assert!(built); + assert!(task.build_used > 0); + assert!(task.work.used() > task.build_used); + task.work.limit = task.work.used() + 1; + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + return; + } + } + panic!("triangle fixture never reached shadow traversal"); +} +#[test] +fn cancellation_is_observed_in_every_ray_image_phase() { + for phase in 0..5 { + let cancel = CancelToken::default(); + let mut task = triangle_task(cancel.clone()); + let mut reached = false; + for _ in 0..100_000 { + let current = match phase { + 0 => task.builder.is_none() && task.bvh.is_none(), + 1 => task.builder.is_some(), + 2 => task.pending.as_ref().is_some_and(|p| p.hit.is_none()), + 3 => task.pending.as_ref().is_some_and(|p| p.hit.is_some()), + _ => task.encoder.is_some(), + }; + if current { + reached = true; + break; + } + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + } + assert!(reached, "phase {phase}"); + cancel.cancel(); + assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled); + } +} +#[test] +fn runtime_presets_reach_the_lighting_consumer() { + for (runtime, expected) in [ + (job::LightingPreset::Neutral, StudioPreset::Neutral), + (job::LightingPreset::WarmCool, StudioPreset::WarmCool), + (job::LightingPreset::KeyRim, StudioPreset::KeyRim), + ] { + let options = RaytraceOptions { preset: Some(runtime), ..Default::default() }; + assert_eq!(lighting(&options).unwrap(), Lighting::preset(expected).unwrap()); + } + let conflict = RaytraceOptions { preset: Some(job::LightingPreset::Neutral), lights: Some(Vec::new()), ..Default::default() }; + assert_eq!(lighting(&conflict).err().unwrap().code, ErrorCode::InvalidRequest); +} +#[test] +fn warm_cool_preset_changes_actual_triangle_png() { + fn render(preset: job::LightingPreset) -> Vec { + let initial = triangle_task(CancelToken::default()); + let options = RaytraceOptions { preset: Some(preset), ..Default::default() }; + let mut request = initial.request.clone(); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(initial.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(16384).unwrap() { + return bytes; + } + } + panic!("preset render did not complete"); + } + let neutral = ::image::load_from_memory(&render(job::LightingPreset::Neutral)).unwrap().to_rgba8(); + let warm = ::image::load_from_memory(&render(job::LightingPreset::WarmCool)).unwrap().to_rgba8(); + assert_ne!(neutral.get_pixel(4, 4), warm.get_pixel(4, 4)); + assert_eq!(neutral.get_pixel(0, 0), warm.get_pixel(0, 0), "background must remain independent of lighting preset"); +} + +#[test] +fn emission_primary_aa_and_reflection_attempts_preserve_single_linear_value() { + for s in [1, 4, 16] { + for r in [1, 4, 16] { + let (mut scene, request, mut options) = emission_fixture(false); + for body in &mut scene.meshes { + let mesh = std::sync::Arc::make_mut(&mut body.mesh); + for p in &mut mesh.positions { + p.x *= 100.0; + p.y *= 100.0; + } + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + options.primary_samples = s; + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "receiver".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: r, + }); + let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [encode8(0.25 / 1.25), encode8(0.5 / 1.5), encode8(0.5), 255], "S{s}/R{r}"); + assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255], "emission does not illuminate the neighboring reflector"); + } + } +} + +#[test] +fn emission_and_directional_point_area_terms_share_one_linear_output_transform() { + let (mut scene, mut request, mut options) = emission_fixture(false); + scene.meshes.truncate(1); + let body = &mut scene.meshes[0]; + for p in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + p.x += 10.0; + } + body.surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()); + scene.bounds = body.mesh.bounds(); + request.width = 1; + request.height = 1; + options.shadows = false; + options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + options.punctual_lights = Some(vec![job::PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 3.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + options.area_lights = Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 5.0, + }]); + options.area_samples = Some(1); + let image = ::image::load_from_memory(&emission_png(scene, request, options)).unwrap().to_rgba8(); + // At normal incidence a white fully rough conductor has BRDF 1/(4*pi). + // Point reference distance is 10 mm; the 4 mm² rectangle contributes 5*4/100. + let direct = (2.0 + 3.0 + 5.0 * 4.0 / 100.0) / (4.0 * std::f64::consts::PI); + let expected = [0.25, 0.5, 1.0].map(|e| encode8((e + direct) / (1.0 + e + direct))); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); +} + +#[test] +fn reflected_hit_adds_surface_emission_with_the_current_path_throughput() { + use std::sync::Arc; + let normal = Vec3::new(1.0, 0.0, 1.0) / 2.0_f64.sqrt(); + let mirror_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, -20.0), Vec3::new(-20.0, 20.0, 20.0)], + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let emitter_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(10.0, -4.0, -2.0), Vec3::new(10.0, -4.0, 2.0), Vec3::new(10.0, 4.0, 2.0), Vec3::new(10.0, 4.0, -2.0)], + normals: vec![-Vec3::X; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let base_color = Vec3::new(0.2, 0.5, 0.75); + let meshes = vec![ + crate::ProductMesh { + transmission: None, + name: "mirror".into(), + mesh: Arc::new(mirror_mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(base_color, 1.0, 0.1, 1.5).unwrap()), + faces: Vec::new(), + }, + crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(emitter_mesh), + color: [0; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }, + ]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let mut request = request(); + request.width = 1; + request.height = 1; + request.camera.distance = 50.0; + request.camera.fov = 0.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + shadows: false, + emissions: Some(vec![job::SurfaceEmission { + body_index: 1, + body: "emitter".into(), + color: [0.25, 0.5, 1.0], + strength: 2.0, + sides: job::EmissionSides::Front, + }]), + reflections: Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "mirror".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: 1, + }), + ..Default::default() + }; + let image = ::image::load_from_memory(&emission_png(ProductScene { meshes, bounds }, request, options)).unwrap().to_rgba8(); + let schlick = (1.0 - 0.5_f64.sqrt()).powi(5); + let expected = [(0.2, 0.5), (0.5, 1.0), (0.75, 2.0)].map(|(f0, emitted)| { + let radiance = (f0 + (1.0 - f0) * schlick) * emitted; + encode8(radiance / (1.0 + radiance)) + }); + assert_eq!(image.get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); +} + +#[test] +fn procedural_effects_change_completed_pngs_independently_and_zero_is_byte_identical() { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use solidcraft_geom::Mesh; + use std::sync::Arc; + 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() + }); + let original = mesh.positions.clone(); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![ProductMesh { + transmission: None, + name: "Coupon".into(), + mesh: mesh.clone(), + color: [180; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.7, 0.5, 0.3), 1.0, 0.4, 1.5).unwrap()), + faces: Vec::new(), + }], + }; + let effect = SurfaceEffect { + body: "Coupon".into(), + frame: Default::default(), + repeat_mm: [12.0, 17.0, 20.0], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }; + let render = |effect: Option| { + let mut request = request(); + request.width = 32; + request.height = 32; + request.camera.distance = 40.0; + request.camera.set_view(crate::StandardView::Top); + let options = RaytraceOptions { surface_effects: effect.map(|e| vec![e]), shadows: false, ..Default::default() }; + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene.clone(), request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("small surface fixture did not complete"); + }; + let baseline = render(None); + assert_eq!(baseline, render(Some(effect.clone()))); + let rough = render(Some(SurfaceEffect { roughness_amplitude: 0.3, ..effect.clone() })); + let bump = render(Some(SurfaceEffect { bump_amplitude_mm: 0.3, ..effect })); + let base = ::image::load_from_memory(&baseline).unwrap().to_rgba8(); + for changed in [&rough, &bump] { + let decoded = ::image::load_from_memory(changed).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), base.dimensions()); + assert_ne!(decoded, base); + for (a, b) in decoded.pixels().zip(base.pixels()) { + assert_eq!(a[3], b[3]); + } + } + assert_ne!(rough, bump); + assert_eq!(mesh.positions, original); +} + +#[test] +fn surface_target_refusals_are_atomic_before_pixels_or_bvh_allocation() { + use crate::surface_patterns::SurfaceEffect; + let effect = + SurfaceEffect { body: "missing".into(), frame: Default::default(), repeat_mm: [20.0; 3], roughness_amplitude: 0.2, bump_amplitude_mm: 0.0 }; + let scene = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY }; + for effects in [vec![effect.clone()], vec![effect.clone(), effect]] { + let options = RaytraceOptions { surface_effects: Some(effects), ..Default::default() }; + let mut request = request(); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidRequest); + } +} + +fn surface_consumer_fixture() -> (ProductScene, ImageRequest, RaytraceOptions) { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use solidcraft_geom::Mesh; + use std::sync::Arc; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 0.0), Vec3::new(20.0, -20.0, 0.0), Vec3::new(20.0, 20.0, 0.0), Vec3::new(-20.0, 20.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + let scene = ProductScene { + bounds: mesh.bounds(), + meshes: vec![ProductMesh { + transmission: None, + name: "Coupon".into(), + mesh, + color: [180; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.7, 0.5, 0.3), 1.0, 0.4, 1.5).unwrap()), + faces: Vec::new(), + }], + }; + let options = RaytraceOptions { + surface_effects: Some(vec![SurfaceEffect { + body: "Coupon".into(), + frame: Default::default(), + repeat_mm: [12.0, 17.0, 20.0], + roughness_amplitude: 0.2, + bump_amplitude_mm: 0.3, + }]), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = request(); + request.width = 1; + request.height = 1; + request.camera.distance = 40.0; + request.camera.set_view(crate::StandardView::Top); + request.raytrace = Some(options.clone()); + (scene, request, options) +} + +fn surface_consumer_png(mut task: ImageTask, quantum: usize) -> Vec { + for _ in 0..200_000 { + let used = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - used <= 4, "surface consumer exceeded public work quantum"); + if let TaskPoll::Complete(png) = poll { + return png; + } + } + panic!("bounded surface consumer did not complete"); +} + +fn surface_constant_environment() -> crate::lighting::environment_input::EnvironmentInput { + use crate::lighting::{HdrSource, environment_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, 4).unwrap() +} + +#[test] +fn surface_effect_shared_hit_reaches_directional_point_area_and_hdr_consumers() { + use crate::job::{DirectionalLightOptions, PunctualLightOptions, RectangleLightOptions}; + use std::sync::Arc; + for mask in 1..16 { + for shadows in [false, true] { + let (scene, mut request, mut options) = surface_consumer_fixture(); + options.shadows = shadows; + if mask & 1 != 0 { + options.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + } + if mask & 2 != 0 { + options.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 3.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + } + if mask & 4 != 0 { + options.area_lights = Some(vec![RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 5.0, + }]); + options.area_samples = Some(1); + } + let effect = options.surface_effects.as_ref().unwrap()[0].prepare().unwrap(); + let changed = effect.apply(scene.meshes[0].surface.unwrap(), Vec3::Z, Vec3::Z, Vec3::ZERO).unwrap(); + let mut reference_scene = scene.clone(); + reference_scene.meshes[0].surface = Some(changed.surface); + Arc::make_mut(&mut reference_scene.meshes[0].mesh).normals.fill(changed.shading_normal); + let mut reference_options = options.clone(); + reference_options.surface_effects = None; + let reference_request = ImageRequest { raytrace: Some(reference_options.clone()), ..request.clone() }; + request.raytrace = Some(options.clone()); + let environment = || if mask & 8 != 0 { Some(surface_constant_environment()) } else { None }; + let expected = surface_consumer_png( + ImageTask::new_with_environment(reference_scene, reference_request, CancelToken::default(), reference_options, environment()) + .unwrap(), + 1, + ); + for quantum in [1, 4, 16384] { + let actual = surface_consumer_png( + ImageTask::new_with_environment(scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()).unwrap(), + quantum, + ); + assert_eq!(actual, expected, "mask={mask}, shadows={shadows}, quantum={quantum}"); + } + } + } +} + +fn surface_at_thirty_two_binding_scan() -> ImageTask { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use solidcraft_geom::Mesh; + use std::sync::Arc; + let (mut scene, mut request, mut options) = surface_consumer_fixture(); + let visible = scene.meshes.pop().unwrap(); + let mut effects = Vec::with_capacity(32); + for index in 0..31 { + let name = format!("unused-{index}"); + scene.meshes.push(ProductMesh { + transmission: None, + name: name.clone(), + mesh: Arc::new(Mesh::default()), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + effects.push(SurfaceEffect { body: name, frame: Default::default(), repeat_mm: [20.0; 3], roughness_amplitude: 0.1, bump_amplitude_mm: 0.0 }); + } + scene.meshes.push(visible); + effects.push(options.surface_effects.take().unwrap().remove(0)); + options.surface_effects = Some(effects); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..20_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some() && !p.surface_ready && p.surface_cursor == 0) { + return task; + } + task.step(1).unwrap(); + } + panic!("did not reach actual unresolved surface scan"); +} + +#[test] +fn thirty_two_surface_bindings_resume_and_refuse_cancel_or_work_exhaustion_without_png() { + let mut task = surface_at_thirty_two_binding_scan(); + for expected_cursor in [4, 8, 12, 16, 20, 24, 28, 32] { + let before = task.work.used(); + assert!(matches!(task.step(16384).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 4); + let pending = task.pending.as_ref().unwrap(); + assert_eq!(pending.surface_cursor, expected_cursor); + assert!(!pending.surface_ready); + assert_eq!(pending.surface_index, if expected_cursor == 32 { Some(31) } else { None }); + assert!(task.pixels.is_empty() && !task.done); + } + let png = surface_consumer_png(task, 4); + assert_eq!(::image::load_from_memory(&png).unwrap().width(), 1); + for cancel in [false, true] { + let mut task = surface_at_thirty_two_binding_scan(); + let before = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = before; + } + assert_eq!(task.step(16384).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert_eq!(task.pending.as_ref().unwrap().surface_cursor, 0); + assert!(task.pixels.is_empty() && !task.done); + } +} + +#[test] +fn surface_effects_reject_ambiguous_targets_and_active_anisotropic_overlap() { + use crate::job::{AnisotropicFaceOptions, AnisotropicOrientation}; + let (scene, mut request, mut options) = surface_consumer_fixture(); + let mut ambiguous = scene.clone(); + ambiguous.meshes.push(scene.meshes[0].clone()); + assert_eq!(admit(&ambiguous, &request, &options).unwrap_err().code, ErrorCode::InvalidRequest); + options.anisotropic_faces[0] = Some(AnisotropicFaceOptions { + body_index: 0, + body_name: "Coupon".into(), + face: 0, + tangent: [1.0, 0.0, 0.0], + orientation: AnisotropicOrientation::Zero, + roughness_x: 0.2, + roughness_y: 0.7, + }); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidRequest); + let identity = options.surface_effects.as_mut().unwrap().first_mut().unwrap(); + identity.roughness_amplitude = 0.0; + identity.bump_amplitude_mm = 0.0; + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).is_ok()); +} + +#[test] +fn reflected_surface_effect_uses_changed_shading_and_resets_before_emitting_secondary_hit() { + use crate::surface_patterns::SurfaceEffect; + use std::sync::Arc; + let normal = Vec3::new(1.0, 0.0, 1.0) / 2.0_f64.sqrt(); + let mirror_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, -20.0), Vec3::new(-20.0, 20.0, 20.0)], + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let emitter_mesh = solidcraft_geom::Mesh { + positions: vec![Vec3::new(10.0, -20.0, -20.0), Vec3::new(10.0, -20.0, 20.0), Vec3::new(10.0, 20.0, 20.0), Vec3::new(10.0, 20.0, -20.0)], + normals: vec![-Vec3::X; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }; + let meshes = vec![ + crate::ProductMesh { + transmission: None, + name: "mirror".into(), + mesh: Arc::new(mirror_mesh), + color: [255; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.2, 0.5, 0.75), 1.0, 0.1, 1.5).unwrap()), + faces: Vec::new(), + }, + crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(emitter_mesh), + color: [0; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }, + ]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let scene = ProductScene { meshes, bounds }; + let effect = SurfaceEffect { + body: "mirror".into(), + frame: Default::default(), + repeat_mm: [12.0, 17.0, 20.0], + roughness_amplitude: 0.2, + bump_amplitude_mm: 0.3, + }; + let changed = effect.prepare().unwrap().apply(scene.meshes[0].surface.unwrap(), normal, normal, Vec3::ZERO).unwrap(); + let mut reference_scene = scene.clone(); + reference_scene.meshes[0].surface = Some(changed.surface); + Arc::make_mut(&mut reference_scene.meshes[0].mesh).normals.fill(changed.shading_normal); + let mut request = request(); + request.width = 1; + request.height = 1; + request.camera.distance = 50.0; + request.camera.fov = 0.0; + request.camera.set_view(crate::StandardView::Top); + for mode in [job::ReflectionMode::Mirror, job::ReflectionMode::RoughSpecular] { + let options = RaytraceOptions { + surface_effects: Some(vec![effect.clone()]), + lights: Some(Vec::new()), + shadows: false, + emissions: Some(vec![job::SurfaceEmission { + body_index: 1, + body: "emitter".into(), + color: [0.25, 0.5, 1.0], + strength: 2.0, + sides: job::EmissionSides::Front, + }]), + reflections: Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "mirror".into(), mode }], + max_bounces: 2, + samples: 16, + }), + ..Default::default() + }; + let mut reference_options = options.clone(); + reference_options.surface_effects = None; + let expected = emission_png(reference_scene.clone(), request.clone(), reference_options); + assert_eq!(emission_png(scene.clone(), request.clone(), options), expected, "mode={mode:?}"); + let decoded = ::image::load_from_memory(&expected).unwrap().to_rgba8(); + assert!(decoded.get_pixel(0, 0).0[..3].iter().any(|value| *value > 0)); + } +} + +fn dielectric_triangle_task(cancel: CancelToken) -> ImageTask { + let task = triangle_task(cancel.clone()); + let mut request = task.request; + let options = RaytraceOptions { + dielectrics: vec![job::DielectricOptions { + body_index: 0, + body_name: "work fixture".into(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.5, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }], + shadows: false, + ..Default::default() + }; + request.raytrace = Some(options.clone()); + let (fixture_scene, _) = task.visibility_owner.into_capture(); + ImageTask::new(fixture_scene, request, cancel, options).unwrap() +} + +#[test] +fn dielectric_branch_traversal_exhausts_the_same_job_work_budget() { + let mut task = dielectric_triangle_task(CancelToken::default()); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.optical.first().and_then(|optical| optical.pending.as_ref()).is_some_and(|state| state.paths > 1) { + assert!(task.work.used() > task.build_used); + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + assert!(!task.done); + return; + } + } + panic!("dielectric branch not reached"); +} + +#[test] +fn completed_dielectric_png_releases_capture_and_path_state() { + let mut task = dielectric_triangle_task(CancelToken::default()); + let weak = std::sync::Arc::downgrade(&task.visibility_owner.source().meshes[0].mesh); + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + assert!(::image::load_from_memory(&png).is_ok()); + assert!(weak.upgrade().is_none()); + assert!(task.optical.is_empty()); + assert!(task.visibility_owner.options().dielectrics.is_empty()); + assert!(task.request.raytrace.is_none()); + assert!(task.bvh.is_none()); + return; + } + } + panic!("dielectric fixture did not complete"); +} + +#[test] +fn dielectric_fixed_stack_and_path_caps_return_typed_failures() { + let ray = Ray::new(Vec3::Z, -Vec3::Z, 0.0, 2.0).unwrap(); + let mut state = DielectricPixel::new(ray); + state.paths = MAX_PATHS; + assert_eq!(state.push(state.path).err().unwrap().code, ErrorCode::LimitExceeded); + state.paths = 1; + state.stack_len = state.stack.len(); + assert_eq!(state.push(state.path).err().unwrap().code, ErrorCode::LimitExceeded); +} + +#[test] +fn dielectric_image_path_applies_radiance_eta_squared_at_each_interface() { + let options = RaytraceOptions { + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.pitch = std::f64::consts::FRAC_PI_2; + let mut task = ImageTask::new(dielectric::tests::scene(dielectric::tests::box_body(2.0)), request, CancelToken::default(), options).unwrap(); + let mut entry = None; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) { + let path = state.path; + if path.boundaries == 1 && path.medium == Some(0) { + // Air -> glass at normal incidence: (1-F0)/n^2 = .96/2.25. + let expected = 0.96 / 2.25; + assert!((path.throughput.x - expected).abs() < 1e-13); + assert!((path.throughput.y - expected).abs() < 1e-13); + assert!((path.throughput.z - expected).abs() < 1e-13); + entry = Some(path.throughput.x); + } + if path.boundaries == 2 && path.medium.is_none() { + // Glass -> air independently multiplies by .96*n^2 = 2.16. + let ratio = path.throughput.x / entry.expect("entry checked before exit"); + assert!((ratio - 2.16).abs() < 1e-13); + return; + } + } + } + panic!("slab's first entry and exit were not observed"); +} + +fn optical_sheet(name: &str, x: f64, z: f64) -> crate::ProductMesh { + use std::sync::Arc; + crate::ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(solidcraft_geom::Mesh { + positions: vec![Vec3::new(x - 20.0, -20.0, z), Vec3::new(x + 20.0, -20.0, z), Vec3::new(x + 20.0, 20.0, z), Vec3::new(x - 20.0, 20.0, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + } +} + +fn optical_input(body_index: usize, body_name: &str, ior: f64) -> job::DielectricOptions { + job::DielectricOptions { + body_index, + body_name: body_name.into(), + boundary: job::DielectricBoundary::ThinSheet, + ior, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + } +} + +fn optical_png(mut task: ImageTask, quantum: usize) -> Vec { + for _ in 0..2_000_000 { + let before = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - before <= 4, "an optical continuation exceeded the shared work quantum"); + if let TaskPoll::Complete(png) = poll { + return png; + } + } + panic!("bounded optical fixture did not finish"); +} + +#[test] +fn dielectric_branches_sum_inside_each_spatial_and_reflection_attempt() { + let mut scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + scene.meshes.push(optical_sheet("unused reflector", 100.0, 0.0)); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let mut baseline = None; + for spatial in [1, 4, 16] { + for attempts in [1, 4, 16] { + let options = RaytraceOptions { + primary_samples: spatial, + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + reflections: Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "unused reflector".into(), mode: job::ReflectionMode::Mirror }], + samples: attempts, + max_bounces: 1, + }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + for quantum in [1, 4, 16384] { + let mut task = ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); + let mut saw_complete_coverage = false; + let mut done = None; + for _ in 0..2_000_000 { + let before = task.work.used(); + let poll = task.step(quantum).unwrap(); + assert!(task.work.used() - before <= 4); + assert!(task.primary_coverage <= u16::from(spatial) * u16::from(attempts)); + if task.emit_spatial_pixel { + assert_eq!(task.primary_coverage, u16::from(spatial) * u16::from(attempts), "branches are not coverage samples"); + saw_complete_coverage = true; + } + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) + && state.path.boundaries > 0 + { + assert!(!task.pending.as_ref().unwrap().repeatable_primary, "selected optical paths have no opaque reuse proof"); + } + if let TaskPoll::Complete(png) = poll { + done = Some(png); + break; + } + } + let png = done.expect("bounded optical AA fixture completes"); + // A four-unit call may commit/reset coverage before yielding. The + // one-unit run observes that state; every quantum checks final bytes. + if spatial != 1 && quantum == 1 { + assert!(saw_complete_coverage); + } + let rgba = ::image::load_from_memory(&png).unwrap().to_rgba8(); + let pixel = rgba.get_pixel(0, 0).0; + assert!(pixel[0] > 150 && pixel[0] == pixel[1] && pixel[1] == pixel[2]); + if let Some(expected) = &baseline { + assert_eq!(&png, expected, "S={spatial}, R={attempts}, quantum={quantum}; branches sum, S/R average"); + } else { + baseline = Some(png); + } + } + } + } +} + +#[test] +fn unit_ior_sheet_rejoins_surface_emission_and_every_existing_light_consumer() { + use job::{DirectionalLightOptions, PunctualLightOptions, RectangleLightOptions}; + for mask in 1..16 { + let (scene, mut request, mut options) = surface_consumer_fixture(); + request.camera.fov = 0.0; + request.camera.distance = 10.0; + // Shadows are deliberately off: this preview's shadow rays conservatively + // treat every dielectric boundary as an opaque blocker. + options.shadows = false; + if mask & 1 != 0 { + options.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]); + } + if mask & 2 != 0 { + options.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 3.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]); + } + if mask & 4 != 0 { + options.area_lights = Some(vec![RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 5.0, + }]); + options.area_samples = Some(4); + } + options.emissions = Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Coupon".into(), + color: [0.1, 0.2, 0.3], + strength: 0.5, + sides: job::EmissionSides::Front, + }]); + request.raytrace = Some(options.clone()); + let environment = || if mask & 8 != 0 { Some(surface_constant_environment()) } else { None }; + let expected = optical_png( + ImageTask::new_with_environment(scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()).unwrap(), + 1, + ); + let mut transmitted_scene = scene; + transmitted_scene.meshes.push(optical_sheet("sheet", 0.0, 5.0)); + transmitted_scene.bounds = transmitted_scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + options.dielectrics = vec![optical_input(1, "sheet", 1.0)]; + request.raytrace = Some(options.clone()); + for quantum in [1, 4, 16384] { + let actual = optical_png( + ImageTask::new_with_environment(transmitted_scene.clone(), request.clone(), CancelToken::default(), options.clone(), environment()) + .unwrap(), + quantum, + ); + assert_eq!(actual, expected, "the same opaque light/surface/emission consumer after transmission; mask={mask}"); + } + } +} + +fn optical_at_eight_selector_scan() -> ImageTask { + let (mut scene, mut request, mut options) = surface_consumer_fixture(); + for i in 0..8 { + let name = format!("unused sheet {i}"); + let index = scene.meshes.len(); + scene.meshes.push(optical_sheet(&name, 100.0 + 50.0 * f64::from(i), 5.0)); + options.dielectrics.push(optical_input(index, &name, 1.5)); + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if task.pending.as_ref().is_some_and(|p| p.hit.is_some()) + && task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|p| !p.ready && p.selector == 0) + { + return task; + } + task.step(1).unwrap(); + } + panic!("actual optical selector scan not reached"); +} + +#[test] +fn eight_optical_selectors_resume_with_cancel_and_work_checks_before_mutation() { + let mut task = optical_at_eight_selector_scan(); + for expected in [4, 8] { + let before = task.work.used(); + assert!(matches!(task.step(16384).unwrap(), TaskPoll::Pending(_))); + assert_eq!(task.work.used() - before, 4); + let state = task.optical[0].pending.as_ref().unwrap(); + assert_eq!(state.selector, expected); + assert!(!state.ready); + assert!(task.pixels.is_empty()); + } + assert!(!optical_png(task, 4).is_empty()); + for cancelled in [false, true] { + let mut task = optical_at_eight_selector_scan(); + let before = task.work.used(); + if cancelled { + task.cancel.cancel(); + } else { + task.work.limit = before; + } + assert_eq!(task.step(4).err().unwrap().code, if cancelled { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert_eq!(task.optical[0].pending.as_ref().unwrap().selector, 0); + assert!(task.pixels.is_empty() && task.encoder.is_none() && !task.done); + } +} + +#[test] +fn optical_reuse_rejects_an_undrained_branch_and_a_selected_primary() { + fn reusable() -> ImageTask { + let mut task = optical_at_eight_selector_scan(); + // Start a fresh coherent request with an unreachable ordinary reflector to + // request R=4, and a spatial grid whose visible receiver remains opaque. + let mut scene = task.visibility_owner.source().clone(); + let mut request = task.request.clone(); + let mut options = task.visibility_owner.options().clone(); + scene.meshes.push(optical_sheet("unused reflector", 1000.0, 0.0)); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + options.primary_samples = 4; + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "unused reflector".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: 4, + }); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + request.raytrace = Some(options.clone()); + task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if task.pending.as_ref().is_some_and(|p| p.light == task.lights.lights().len() + 1) { + assert!(task.optical[0].pending.is_none(), "only drained optics reach the completed opaque marker"); + return task; + } + task.step(1).unwrap(); + } + panic!("completed nonselected primary marker not reached"); + } + for pending_branch in [false, true] { + let mut task = reusable(); + if pending_branch { + task.optical[0].pending = Some(DielectricPixel::new(task.pending.as_ref().unwrap().ray)); + } else { + let (fixture_scene, mut fixture_options) = task.visibility_owner.into_capture(); + fixture_options.dielectrics[0].body_index = 0; + fixture_options.dielectrics[0].body_name = "Coupon".into(); + task.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + } + let before = task.primary_coverage; + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::InvalidScene); + assert_eq!(task.primary_coverage, before); + assert!(task.pixels.is_empty()); + } +} + +#[test] +fn optical_admission_bills_capacity_and_refuses_ambiguous_effect_and_environment_contracts() { + let scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + let mut options = RaytraceOptions { dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], ..Default::default() }; + let name = scene.meshes[0].name.clone(); + let bytes = options.retained_bytes().unwrap(); + assert_eq!( + bytes, + options.dielectrics.capacity() as u64 * std::mem::size_of::() as u64 + + options.dielectrics[0].body_name.capacity() as u64 + ); + let mut request = dielectric::tests::request(options.clone()); + let with_optics = admit(&scene, &request, &options).unwrap(); + let plain = RaytraceOptions::default(); + let plain_request = ImageRequest { raytrace: Some(plain.clone()), ..request.clone() }; + let without_optics = admit(&scene, &plain_request, &plain).unwrap(); + assert_eq!( + with_optics.estimated_total_bytes - without_optics.estimated_total_bytes, + bytes + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + std::mem::size_of::() as u64 + ); + options.surface_effects = Some(vec![crate::surface_patterns::SurfaceEffect { + body: name, + frame: Default::default(), + repeat_mm: [10.0; 3], + roughness_amplitude: 0.1, + bump_amplitude_mm: 0.0, + }]); + request.raytrace = Some(options.clone()); + assert_eq!(admit(&scene, &request, &options).unwrap_err().code, ErrorCode::InvalidScene); + options.surface_effects.as_mut().unwrap()[0].roughness_amplitude = 0.0; + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).is_ok(), "an identity opaque effect does not change the geometric boundary"); + options.environment = Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }); + request.raytrace = Some(options.clone()); + assert_eq!( + options.validate_environment_reflections(&scene).unwrap_err().code, + ErrorCode::InvalidRequest, + "the same guard is called by engine preflight and host admission" + ); + assert_eq!( + ImageTask::new_with_environment( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + Some(surface_constant_environment()) + ) + .err() + .unwrap() + .code, + ErrorCode::InvalidRequest + ); + options.dielectrics = Vec::with_capacity(9); + assert_eq!(options.validate().unwrap_err().code, ErrorCode::InvalidRequest); +} + +#[test] +fn captured_clear_coat_keeps_direct_shading_but_refuses_unmatched_cpu_transport() { + let (mut scene, mut request, mut options) = emission_fixture(false); + let coat = crate::clear_coat::ClearCoat::new(0.8, 0.2, 1.5).unwrap(); + let surface = OpaqueSurface::new(Vec3::new(0.4, 0.3, 0.2), 0.0, 0.4, 1.5).unwrap().with_clear_coat(coat); + scene.meshes[0].surface = Some(surface); + request.raytrace = Some(options.clone()); + admit(&scene, &request, &options).unwrap(); + options.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "emitter".into(), mode: job::ReflectionMode::RoughSpecular }], + max_bounces: 1, + samples: 1, + }); + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).unwrap_err().message.contains("clear-coat transport")); + scene.meshes[0].surface = None; + scene.meshes[0].faces.push(crate::FaceAppearance { face: 0, color: [255; 3], opacity: 1.0, surface: Some(surface), transmission: None }); + assert!(admit(&scene, &request, &options).unwrap_err().message.contains("clear-coat transport")); +} + +#[test] +fn pending_pixel_heap_slot_stays_single_and_reuses_storage_until_completion() { + let mut task = triangle_task(CancelToken::default()); + let initial = task.pending.0.as_ptr(); + assert_eq!(task.pending.0.capacity(), 1); + assert!(task.pending.is_none()); + assert!(std::mem::size_of::() <= 4096); + let expected = admit(task.visibility_owner.source(), &task.request, task.visibility_owner.options()).unwrap(); + assert_eq!(task.admission.estimated_total_bytes, expected.estimated_total_bytes); + assert!(expected.preparation_bytes >= PendingPixelSlot::required_bytes()); + let mut seen = false; + let mut completed = false; + for _ in 0..100_000 { + match task.step(1).unwrap() { + TaskPoll::Pending(_) => { + assert_eq!(task.pending.0.capacity(), 1); + assert_eq!(task.pending.0.as_ptr(), initial, "samples must reuse the one admitted continuation slot"); + assert!(task.pending.0.len() <= 1); + seen |= task.pending.is_some(); + } + TaskPoll::Complete(png) => { + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(task.pending.0.capacity(), 0, "completed task releases continuation storage before its lease is shrunk"); + assert!(task.pending.is_none()); + completed = true; + break; + } + } + } + assert!(completed, "fixture must complete within its bounded test work"); + assert!(seen, "fixture must exercise a live resumable pixel"); +} + +#[test] +fn cancelled_pending_pixel_allocation_is_refused_before_any_continuation() { + let cancel = CancelToken::default(); + cancel.cancel(); + assert_eq!(PendingPixelSlot::new(&cancel).err().unwrap().code, ErrorCode::Cancelled); +} + +fn nested_optical_task() -> ImageTask { + let (scene, mut options) = dielectric::tests::nested_fixture(false); + for medium in &mut options.dielectrics { + medium.ior = if medium.body_name == "Outer" { 1.5 } else { 2.0 }; + medium.absorption_per_mm = [0.0; 3]; + } + ImageTask::new_with_environment_and_nested(scene, dielectric::tests::request(options.clone()), CancelToken::default(), options, None, true) + .unwrap() +} + +#[test] +fn nested_image_interfaces_use_actual_parent_ior_and_restore_it_on_exit() { + let mut task = nested_optical_task(); + let outer_entry = 0.96 / 2.25; + let inner_entry = outer_entry * (27.0 / 49.0); + let inner_exit = inner_entry * (256.0 / 147.0); + let expected = [(1, Some(0), outer_entry), (2, Some(1), inner_entry), (3, Some(0), inner_exit), (4, None, inner_exit * 2.16)]; + let mut next = 0; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) { + let (depth, medium, throughput) = expected[next]; + if state.path.boundaries == depth && state.path.medium == medium { + assert!((state.path.throughput.x - throughput).abs() < 1e-12); + assert!((state.path.throughput.y - throughput).abs() < 1e-12); + assert!((state.path.throughput.z - throughput).abs() < 1e-12); + next += 1; + if next == expected.len() { + return; + } + } + } + } + panic!("nested first transmitted path did not cross all four interfaces"); +} + +#[test] +fn nested_paths_keep_one_unit_work_cancellation_and_total_budget_contracts() { + for cancel in [false, true] { + let mut task = nested_optical_task(); + let mut observed = false; + for _ in 0..100_000 { + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 1, "one-unit continuation overspent its quantum"); + if task.optical.first().and_then(|optical| optical.pending.as_ref()).is_some_and(|state| state.path.medium == Some(1)) { + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert!(!task.done); + observed = true; + break; + } + } + assert!(observed, "nested interior was never reached"); + } +} + +#[test] +fn nested_admission_bills_parent_table_and_keeps_geometry_and_camera_refusals() { + let (scene, options) = dielectric::tests::nested_fixture(false); + let request = dielectric::tests::request(options.clone()); + let admitted = admit_with_nested(&scene, &request, &options, true).unwrap(); + let original = options.retained_dielectric_bytes().unwrap() + + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() + + std::mem::size_of::() as u64; + assert!(admitted.preparation_bytes >= original); + assert!(std::mem::size_of::() >= std::mem::size_of::<[Option; MAX_OVERRIDES]>()); + + let mut invalid = scene.clone(); + std::sync::Arc::make_mut(&mut invalid.meshes[1].mesh).triangles.pop(); + assert!(admit_with_nested(&invalid, &request, &options, true).is_err()); + + let mut inside = request.clone(); + inside.camera.distance = 0.1; + inside.camera.target = Vec3::new(0.0, 0.0, 2.0); + let mut task = ImageTask::new_with_environment_and_nested(scene, inside, CancelToken::default(), options, None, true).unwrap(); + for _ in 0..100_000 { + match task.step(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("inside a dielectric")); + return; + } + Ok(TaskPoll::Pending(_)) => {} + Ok(TaskPoll::Complete(_)) => panic!("inside camera must not publish"), + } + } + panic!("inside camera was not refused"); +} + +fn close_gap_nested_task(gap: f64, positive: bool) -> ImageTask { + use std::sync::Arc; + let mut outer = dielectric::tests::box_body(3.0); + outer.name = "OuterGap".into(); + for p in &mut Arc::make_mut(&mut outer.mesh).positions { + *p = Vec3::new(p.x * 0.2, p.y * 0.2, p.z + 1.0); + } + let mut inner = dielectric::tests::box_body(2.0); + inner.name = "InnerGap".into(); + for p in &mut Arc::make_mut(&mut inner.mesh).positions { + *p = Vec3::new(p.x * 0.1, p.y * 0.1, if p.z == 0.0 { 1.0 + gap } else { 3.0 }); + } + let mut scene = dielectric::tests::scene(outer); + scene.meshes.push(inner); + let options = RaytraceOptions { + dielectrics: scene + .meshes + .iter() + .enumerate() + .map(|(body_index, body)| job::DielectricOptions { + body_index, + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }) + .collect(), + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.set_view(if positive { crate::StandardView::Bottom } else { crate::StandardView::Top }); + request.camera.target = Vec3::new(0.0, 0.0, 2.5); + request.camera.fov = 0.0; + ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap() +} + +#[test] +fn positive_one_ulp_nested_gap_and_separated_control_visit_every_real_interface() { + for gap in [f64::EPSILON, 0.25] { + for positive in [false, true] { + let mut task = close_gap_nested_task(gap, positive); + let points = if positive { [1.0, 1.0 + gap, 3.0, 4.0] } else { [4.0, 3.0, 1.0 + gap, 1.0] }; + let media = [Some(0), Some(1), Some(0), None]; + let mut next = 0; + let mut completed = false; + for _ in 0..100_000 { + match task.step(1).unwrap() { + TaskPoll::Pending(_) => { + if next < points.len() + && let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) + && state.path.boundaries == next as u8 + 1 + { + assert_eq!(state.path.medium, media[next]); + assert_eq!(state.path.segment_start.z, points[next]); + assert_eq!(state.path.ray.origin(), state.path.segment_start, "propagation and Beer start share one physical point"); + assert_eq!(state.path.throughput, Vec3::new(1.0, 1.0, 1.0)); + next += 1; + } + } + TaskPoll::Complete(png) => { + assert_eq!(next, 4, "an admitted interface was skipped"); + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [188, 188, 188, 255]); + completed = true; + break; + } + } + } + assert!(completed, "close-gap image failed to complete"); + } + } +} + +#[test] +fn nested_reflected_route_keeps_child_beer_then_restores_parent_from_both_sides() { + for positive in [false, true] { + let (scene, mut options) = dielectric::tests::nested_fixture(false); + for medium in &mut options.dielectrics { + medium.ior = if medium.body_name == "Outer" { 1.5 } else { 2.0 }; + } + let mut request = dielectric::tests::request(options.clone()); + request.camera.set_view(if positive { crate::StandardView::Bottom } else { crate::StandardView::Top }); + request.camera.target = Vec3::new(0.0, 0.0, 2.0); + request.camera.fov = 0.0; + let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let (near, far) = if positive { (1.0, 3.0) } else { (3.0, 1.0) }; + let factor = (0.96 / 2.25) * (27.0 / 49.0) / 49.0; + let reflected = Vec3::new(factor * (-0.1_f64 - 0.3 * 2.0).exp(), factor * (-0.2_f64 - 0.4 * 2.0).exp(), factor); + let returned = dielectric::multiply(reflected, Vec3::new((-0.3_f64 * 2.0).exp(), (-0.4_f64 * 2.0).exp(), 1.0)) * (256.0 / 147.0); + let mut saw_reflected = false; + let mut restored = false; + for _ in 0..1_000_000 { + if let TaskPoll::Complete(_) = task.step(1).unwrap() { + break; + } + let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) else { continue }; + let path = state.path; + if path.boundaries == 3 && path.medium == Some(1) && path.segment_start.z == far { + assert!((path.throughput - reflected).len() < 1e-12); + assert_eq!(path.ray.origin(), path.segment_start); + assert!(path.ray.direction().z * if positive { -1.0 } else { 1.0 } > 0.0); + saw_reflected = true; + } + if saw_reflected && path.boundaries == 4 && path.medium == Some(0) && path.segment_start.z == near { + assert!((path.throughput - returned).len() < 1e-12); + assert_eq!(path.ray.origin(), path.segment_start); + restored = true; + break; + } + } + assert!(saw_reflected && restored, "actual reflected child route never restored its parent"); + } +} + +#[test] +fn exact_box_launch_is_opt_in_and_legacy_default_origin_is_preserved() { + for nested in [false, true] { + let mut material = dielectric::tests::input(job::DielectricBoundary::ClosedBox); + material.ior = 1.0; + let options = RaytraceOptions { dielectrics: vec![material], lights: Some(Vec::new()), shadows: false, ..Default::default() }; + let request = dielectric::tests::request(options.clone()); + let mut task = ImageTask::new_with_environment_and_nested( + dielectric::tests::scene(dielectric::tests::box_body(2.0)), + request, + CancelToken::default(), + options, + None, + nested, + ) + .unwrap(); + let mut observed = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) + && state.path.boundaries == 1 + && state.path.medium == Some(0) + { + assert_eq!(state.path.segment_start.z, 2.0); + if nested { + assert_eq!(state.path.ray.origin(), state.path.segment_start); + } else { + assert!(state.path.ray.origin().z < state.path.segment_start.z, "default must retain its original inward offset"); + } + observed = true; + break; + } + } + assert!(observed, "first box entry was not observed"); + } +} + +// Progressive smooth-optics unit: original tests WRITTEN, NOT COMPILED OR RUN. +pub(super) fn progressive_optics_source( + boundary: job::DielectricBoundary, + thickness: f64, + ior: f64, + samples: u32, +) -> (ProductScene, ImageRequest, RaytraceOptions) { + let body = match boundary { + job::DielectricBoundary::ThinSheet => optical_sheet("captured slab@occurrence-2", 0.0, 0.0), + job::DielectricBoundary::ClosedBox => dielectric::tests::box_body(thickness), + }; + let mut medium = dielectric::tests::input(boundary); + medium.ior = ior; + medium.thickness_mm = if boundary == job::DielectricBoundary::ThinSheet { thickness } else { 0.0 }; + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 97 }), + dielectrics: vec![medium], + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + request.camera.pitch = std::f64::consts::FRAC_PI_2; + (dielectric::tests::scene(body), request, options) +} + +#[derive(Debug, PartialEq)] +struct OpticalProgressiveRun { + checkpoints: Vec<(u32, Vec)>, + png: Vec, + film: Vec<[u64; 3]>, + primaries: Vec<(usize, u32, [u64; 6])>, + work: u64, +} + +fn finish_optical_progressive(mut task: ImageTask, quantum: usize) -> OpticalProgressiveRun { + let mut checkpoints = Vec::new(); + let mut film = None; + let mut primaries = Vec::new(); + let mut previous_sample = None; + let target = task.visibility_owner.options().progressive.unwrap().samples_per_pixel; + for _ in 0..2_000_000 { + if let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.samples() == target + { + film.get_or_insert_with(|| { + (0..task.request.width as usize * task.request.height as usize) + .map(|pixel| progressive.film.pixel(pixel).unwrap().0.map(f64::to_bits)) + .collect() + }); + } + let poll = task.step_with_previews(quantum).unwrap(); + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + let identity = state.camera_sample.unwrap(); + assert_eq!(identity, (task.pixel, task.progressive.as_ref().unwrap().film.samples())); + assert!(task.primary_coverage <= 1, "Fresnel branches cannot become coverage samples"); + if previous_sample != Some(identity) { + // Each fixture hits certified geometry; even the four-unit call + // yields before the first boundary can replace its camera ray. + assert_eq!(state.path.boundaries, 0); + let origin = state.path.ray.origin(); + let direction = state.path.ray.direction(); + primaries.push(( + identity.0, + identity.1, + [origin.x.to_bits(), origin.y.to_bits(), origin.z.to_bits(), direction.x.to_bits(), direction.y.to_bits(), direction.z.to_bits()], + )); + previous_sample = Some(identity); + } + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + assert!(task.pending.is_none()); + assert!(task.optical.first().unwrap().pending.is_none()); + let (_, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!((covered, count), (samples_per_pixel, samples_per_pixel)); + checkpoints.push((samples_per_pixel, png)); + } + ImagePoll::Complete(png) => { + assert!(task.optical.is_empty() && task.progressive.is_none()); + return OpticalProgressiveRun { checkpoints, png, film: film.unwrap(), primaries, work: task.work.used() }; + } + } + } + panic!("original optical progressive fixture did not complete"); +} + +#[test] +fn progressive_optical_trees_commit_once_and_keep_absolute_rays_across_quanta() { + for boundary in [job::DielectricBoundary::ThinSheet, job::DielectricBoundary::ClosedBox] { + let (scene, request, options) = progressive_optics_source(boundary, 2.0, 1.5, 5); + let one = finish_optical_progressive(ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(), 1); + let four = finish_optical_progressive(ImageTask::new(scene, request, CancelToken::default(), options).unwrap(), 4); + assert_eq!(one, four, "film bits, actual primary rays, checkpoints, final and total work agree"); + assert_eq!(one.primaries.len(), 5); + assert_eq!(one.checkpoints.iter().map(|c| c.0).collect::>(), [1, 2, 3, 4]); + assert_ne!(one.primaries[0].2, one.primaries[1].2, "fresh camera jitter, no repeated completed sample"); + let linear = f64::from_bits(one.film[0][0]); + assert!(linear > 0.999 && linear <= 1.0 + 1e-12, "bounded eight-boundary lossless response, not alpha or branch averaging"); + assert_eq!(::image::load_from_memory(&one.png).unwrap().to_rgba8().get_pixel(0, 0).0, [188, 188, 188, 255]); + } +} + +#[test] +fn progressive_optical_checkpoint_is_the_exact_shorter_job_prefix() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 5); + let run = finish_optical_progressive(ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(), 1); + for (samples, png) in &run.checkpoints { + let mut prefix_options = options.clone(); + prefix_options.progressive.as_mut().unwrap().samples_per_pixel = *samples; + let prefix_request = ImageRequest { raytrace: Some(prefix_options.clone()), ..request.clone() }; + let prefix = finish_optical_progressive(ImageTask::new(scene.clone(), prefix_request, CancelToken::default(), prefix_options).unwrap(), 2); + assert_eq!(&prefix.png, png); + assert_eq!(prefix.primaries, run.primaries[..*samples as usize]); + } +} + +#[test] +fn progressive_optical_film_uses_real_beer_distance_for_thin_and_closed_controls() { + for boundary in [job::DielectricBoundary::ThinSheet, job::DielectricBoundary::ClosedBox] { + for thickness in [2.0, 8.0] { + let (scene, mut request, mut options) = progressive_optics_source(boundary, thickness, 1.0, 3); + options.dielectrics[0].absorption_per_mm = [0.1, 0.2, 0.0]; + request.raytrace = Some(options.clone()); + let run = finish_optical_progressive(ImageTask::new(scene, request, CancelToken::default(), options).unwrap(), 1); + for (actual, sigma) in run.film[0].into_iter().zip([0.1_f64, 0.2, 0.0]) { + assert!((f64::from_bits(actual) - (-sigma * thickness).exp()).abs() < 1e-10); + } + assert_eq!(run.primaries.len(), 3); + } + } +} + +#[test] +fn progressive_closed_optics_use_four_percent_fresnel_and_snell_eta_transport() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut saw_entry = false; + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + if state.path.boundaries == 1 && state.path.medium == Some(0) { + let entry = 0.96 / 2.25; + assert!((state.path.throughput.x - entry).abs() < 1e-13); + assert!((state.path.ray.direction() + Vec3::Z).len() < 1e-12); + let reflected = state.stack.iter().flatten().find(|path| path.boundaries == 1 && path.medium.is_none()).unwrap(); + assert!((reflected.throughput.x - 0.04).abs() < 1e-13); + saw_entry = true; + } + if saw_entry && state.path.boundaries == 2 && state.path.medium.is_none() { + assert!((state.path.throughput.x - 0.96 * 0.96).abs() < 1e-12); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0, "first transmitted leaf is not a complete film sample"); + return; + } + } + } + panic!("real progressive slab interfaces not reached"); +} + +#[test] +fn progressive_nested_optics_preserve_parent_beer_distance_and_require_opt_in() { + for reverse in [false, true] { + let (scene, mut options) = dielectric::tests::nested_fixture(reverse); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 19 }); + let mut request = dielectric::tests::request(options.clone()); + request.camera.target = Vec3::new(0.0, 0.0, 2.0); + request.camera.distance = 6.0; + request.camera.fov = 0.0; + assert!(admit(&scene, &request, &options).is_err()); + let run = finish_optical_progressive( + ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(), + 1, + ); + for (actual, exponent) in run.film[0].into_iter().zip([-0.8_f64, -1.2, 0.0]) { + assert!((f64::from_bits(actual) - exponent.exp()).abs() < 1e-10); + } + assert_eq!(::image::load_from_memory(&run.png).unwrap().to_rgba8().get_pixel(0, 0).0, [151, 132, 188, 255]); + } +} + +#[test] +fn progressive_optical_sample_identity_and_commit_barriers_refuse_partial_trees() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ThinSheet, 1.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some() { + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert!(task.finish_sample(Vec3::new(1.0, 1.0, 1.0)).is_err()); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + task.optical.first_mut().unwrap().pending.as_mut().unwrap().camera_sample = Some((0, 1)); + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("absolute camera sample")); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + return; + } + } + panic!("optical camera sample not reached"); +} + +#[test] +fn progressive_optics_keep_cancellation_work_exhaustion_and_geometry_refusals() { + for cancel in [false, true] { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut stopped = false; + for _ in 0..100_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.medium.is_some()) { + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + stopped = true; + break; + } + } + assert!(stopped); + } + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut open = scene.clone(); + std::sync::Arc::make_mut(&mut open.meshes[0].mesh).triangles.pop(); + assert!(admit(&open, &request, &options).is_err()); + let mut alpha = scene.clone(); + alpha.meshes[0].opacity = 0.5; + assert!(admit(&alpha, &request, &options).is_err()); + let mut identity = options.clone(); + identity.dielectrics[0].body_name = "stale optical target".into(); + let wrong = ImageRequest { raytrace: Some(identity.clone()), ..request }; + assert!(admit(&scene, &wrong, &identity).is_err()); +} + +#[test] +fn progressive_closed_optics_tir_keeps_medium_and_generates_no_transmitted_branch() { + let (scene, request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + // Observe a real certified transmitted interior, then exercise its actual + // consumer with an analytic 3-4-5 internal direction at the top face. + // Camera-inside admission is not bypassed for any submitted request. + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.boundaries == 1 && s.path.medium == Some(0)) { + let ray = Ray::new(Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.8, 0.0, 0.6), 0.0, 100.0).unwrap(); + let state = task.optical.first_mut().unwrap().pending.as_mut().unwrap(); + state.stack.fill(None); + state.stack_len = 0; + state.path.ray = ray; + state.path.segment_start = ray.origin(); + state.ready = false; + resume_optical_path(task.pending.as_mut().unwrap(), state.path, task.lights.lights().len()).unwrap(); + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + let state = task.optical.first().unwrap().pending.as_ref().unwrap(); + if state.path.boundaries == 2 { + assert_eq!(state.path.medium, Some(0)); + assert!(state.path.ray.direction().z < 0.0); + assert_eq!(state.stack_len, 0, "TIR cannot enqueue a transmitted path"); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + return; + } + } + panic!("TIR boundary not consumed"); + } + } + panic!("certified interior not reached"); +} + +#[test] +fn progressive_oblique_box_uses_snell_direction_and_geometric_path_length() { + let (scene, mut request, mut options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + options.dielectrics[0].absorption_per_mm = [0.1, 0.0, 0.0]; + request.raytrace = Some(options.clone()); + request.camera.pitch = std::f64::consts::FRAC_PI_3; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut incident = None; + let mut entry = None; + for _ in 0..100_000 { + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) else { continue }; + if state.path.boundaries == 0 { + incident = Some(state.path.ray.direction()); + } + if state.path.boundaries == 1 && state.path.medium == Some(0) { + let d = incident.unwrap(); + let tx = d.x / 1.5; + let ty = d.y / 1.5; + let tz = -(1.0 - tx * tx - ty * ty).sqrt(); + assert!((state.path.ray.direction() - Vec3::new(tx, ty, tz)).len() < 1e-12); + entry = Some((state.path.segment_start, state.path.throughput, tz)); + } + if state.path.boundaries == 2 && state.path.medium.is_none() { + let (point, throughput, tz) = entry.unwrap(); + let distance = 2.0 / -tz; + assert!((state.path.segment_start.dist(point) - distance).abs() < 1e-10); + assert!((state.path.ray.direction() - incident.unwrap()).len() < 1e-12); + // Exit Fresnel and eta factors are achromatic. Their ratio cancels + // between red and green, leaving only exp(-sigma * REAL distance). + let attenuation = (state.path.throughput.x / state.path.throughput.y) / (throughput.x / throughput.y); + assert!((attenuation - (-0.1 * distance).exp()).abs() < 1e-10); + return; + } + } + panic!("oblique progressive entry/exit not reached"); +} + +#[test] +fn progressive_nested_optics_still_refuse_contacts_and_interior_cameras() { + let (mut scene, mut options) = dielectric::tests::nested_fixture(false); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 19 }); + let request = dielectric::tests::request(options.clone()); + for point in &mut std::sync::Arc::make_mut(&mut scene.meshes[1].mesh).positions { + point.z += 1.0; + } + assert!(admit_with_nested(&scene, &request, &options, true).is_err(), "inner top touches outer top"); + let (scene, mut request, options) = progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, 3); + request.camera.target = Vec3::new(0.0, 0.0, 1.0); + request.camera.distance = 0.1; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + match task.step_with_previews(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("inside a dielectric")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + return; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("interior camera cannot publish a checkpoint or final"), + } + } + panic!("interior progressive camera not refused"); +} + +// Original regression implementation guided by Kernel Specialist's analytic +// identity-shell counterexample (FINDING5282bf86 / proposal dae7f679). SOURCE +// ONLY, WRITTEN NOT RUN; expectations are physical, never recorded output. +pub(super) fn straight_identity_shells_source(count: usize, progressive: bool, absorbing: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + assert!((1..=8).contains(&count)); + let mut meshes = Vec::with_capacity(8); + let mut dielectrics = Vec::with_capacity(8); + for index in 0..count { + let h = (count - index) as f64; + let mut body = dielectric::tests::box_body(2.0 * h); + body.name = format!("Straight identity shell {index}"); + for point in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + *point = Vec3::new(if point.x < 0.0 { -(16.0 + h) } else { 16.0 + h }, if point.y < 0.0 { -(16.0 + h) } else { 16.0 + h }, point.z - h); + } + let sigma = if absorbing { 0.01 * (index + 1) as f64 } else { 0.0 }; + dielectrics.push(job::DielectricOptions { + body_index: index, + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: [sigma, 2.0 * sigma, 0.0], + thickness_mm: 0.0, + }); + meshes.push(body); + } + assert!(dielectrics.capacity() <= 8); + let bounds = meshes.iter().fold(Aabb3::EMPTY, |a, body| a.union(&body.mesh.bounds())); + let options = RaytraceOptions { + dielectrics, + progressive: progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 71 }), + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.background = [188; 3]; + request.camera.target = Vec3::ZERO; + request.camera.distance = 20.0; + request.camera.yaw = 0.0; + request.camera.pitch = std::f64::consts::FRAC_PI_2; + request.camera.fov = 0.0; + (ProductScene { meshes, bounds }, request, options) +} + +pub(super) fn straight_shells_expected_linear(count: usize, absorbing: bool) -> [f64; 3] { + // Each shell's active parent interval totals2mm, including the innermost + // 2mm slab. Sum 2*.01*(1+...+N)=.01*N*(N+1); green doubles sigma. + let tau = if absorbing { 0.01 * (count * (count + 1)) as f64 } else { 0.0 }; + [(-tau).exp(), (-2.0 * tau).exp(), 1.0] +} + +pub(super) fn straight_expected_pixel(linear: [f64; 3]) -> [u8; 4] { + // Independent documented zero-EV Reinhard and IEC sRGB equations, not the + // renderer's compositor/map_to_display/encode8 or a prior output capture. + let rgb = linear.map(|v| { + let mapped = v / (1.0 + v); + let encoded = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; + (encoded * 255.0 + 0.5).floor() as u8 + }); + [rgb[0], rgb[1], rgb[2], 255] +} + +fn complete_straight_shells(mut task: ImageTask, expected_crossings: u8, expected_linear: [f64; 3]) -> Vec { + let progressive = task.visibility_owner.options().progressive; + let mut final_linear = None; + let mut maximum = 0; + let mut final_png = None; + assert_eq!(task.optical.first().unwrap().straight_limit, Some(expected_crossings)); + for _ in 0..1_000_000 { + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() == progressive.unwrap().samples_per_pixel + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (3, 3)); + final_linear = Some(rgb); + } + let before = task.work.used(); + let poll = task.step_with_previews(1).unwrap(); + // PNG row/hash charges are the unchanged resolve contract. During + // optical traversal/interface stages one unit cannot overspend. + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + assert!(task.work.used() - before <= 1); + assert_eq!(state.stack_len, 0, "zero Fresnel reflection creates no pending branch"); + assert_eq!(state.paths, u16::from(state.path.boundaries) + 1); + maximum = maximum.max(state.path.boundaries); + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, .. } => { + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, straight_expected_pixel(expected_linear)); + assert!(task.optical.first().unwrap().pending.is_none()); + } + ImagePoll::Complete(png) => { + final_png = Some(png); + break; + } + } + } + assert_eq!(maximum, expected_crossings, "every real geometric interface was traversed"); + if progressive.is_some() { + for (actual, expected) in final_linear.unwrap().into_iter().zip(expected_linear) { + assert!((actual - expected).abs() < 1e-11, "physical parent-only Beer path length"); + } + } + let png = final_png.expect("certified finite straight path must complete"); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, straight_expected_pixel(expected_linear)); + png +} + +#[test] +fn straight_identity_shells_four_control_five_minimum_and_eight_maximum_reach_environment() { + for progressive in [false, true] { + for count in [4, 5, 8] { + let (scene, request, options) = straight_identity_shells_source(count, progressive, false); + options.validate().unwrap(); + assert!(admit(&scene, &request, &options).is_err(), "nesting still requires explicit opt-in"); + admit_with_nested(&scene, &request, &options, true).unwrap(); + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let png = complete_straight_shells(task, (2 * count) as u8, [1.0; 3]); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [188, 188, 188, 255]); + } + } +} + +#[test] +fn straight_identity_shells_keep_actual_beer_parent_intervals_past_eight_crossings() { + for progressive in [false, true] { + for count in [4, 5, 8] { + let (scene, request, options) = straight_identity_shells_source(count, progressive, true); + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let _ = complete_straight_shells(task, (2 * count) as u8, straight_shells_expected_linear(count, true)); + } + } +} + +#[test] +fn straight_mixed_certificates_derive_two_per_box_and_one_per_sheet_without_extra_stack() { + let (mut scene, mut request, mut options) = straight_identity_shells_source(5, true, false); + for index in 0..3 { + let name = format!("Straight external sheet {index}"); + let body_index = scene.meshes.len(); + scene.meshes.push(optical_sheet(&name, 0.0, 6.0 + index as f64)); + options.dielectrics.push(optical_input(body_index, &name, 1.0)); + } + assert_eq!(options.dielectrics.len(), 8); + assert!(options.dielectrics.capacity() <= 8); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, body| a.union(&body.mesh.bounds())); + request.raytrace = Some(options.clone()); + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let _ = complete_straight_shells(task, 13, [1.0; 3]); +} + +#[test] +fn straight_policy_requires_exact_unit_indices_and_no_selected_opaque_reflector() { + assert_eq!(MAX_BOUNDARIES, 8); + assert_eq!(MAX_PATHS, 511); + let (scene, request, options) = straight_identity_shells_source(5, false, false); + for ior in [1.0_f64.next_up(), 1.5] { + let mut changed = options.clone(); + changed.dielectrics[2].ior = ior; + let request = ImageRequest { raytrace: Some(changed.clone()), ..request.clone() }; + let task = ImageTask::new_with_environment_and_nested(scene.clone(), request, CancelToken::default(), changed, None, true).unwrap(); + assert_eq!(task.optical.first().unwrap().straight_limit, None, "no epsilon-index shortcut or new rejection of legacy refracting input"); + } + let mut scene = scene; + let mut changed = options; + scene.meshes.push(optical_sheet("Separate opaque reflector", 100.0, 0.0)); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, body| a.union(&body.mesh.bounds())); + changed.reflections = Some(job::ReflectionOptions { + bodies: vec![job::ReflectionBody { body: "Separate opaque reflector".into(), mode: job::ReflectionMode::Mirror }], + max_bounces: 1, + samples: 1, + }); + let request = ImageRequest { raytrace: Some(changed.clone()), ..request }; + let task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), changed, None, true).unwrap(); + assert_eq!(task.optical.first().unwrap().straight_limit, None); + assert!(task.optical.first().unwrap().pending.is_none()); +} + +#[test] +fn straight_identity_transport_still_charges_and_can_cancel_or_exhaust_inside_deep_chain() { + for cancel in [false, true] { + let (scene, request, options) = straight_identity_shells_source(8, true, true); + let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + let mut observed = false; + for _ in 0..200_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.boundaries == 9) { + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + observed = true; + break; + } + } + assert!(observed, "real ninth crossing must be reached before the stop"); + } +} + +#[test] +fn straight_crossing_bound_corruption_is_typed_error_not_a_successful_black_tail() { + let (scene, request, options) = straight_identity_shells_source(5, true, false); + let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); + // Controlled invariant unit, distinct from the unchanged valid E2E fixtures: + // an impossible internal policy must fail at a real subsequent interface. + task.optical.first_mut().unwrap().straight_limit = Some(1); + for _ in 0..200_000 { + match task.step_with_previews(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::InvalidScene); + assert!(error.message.contains("straight optical crossing bound exceeded")); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + return; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("bound inconsistency cannot publish success"), + } + } + panic!("unexpected extra crossing was not refused"); +} + +// Original camera-to-final TIR supplement, AFTER frozen progressive optics. +// WRITTEN NOT COMPILED/RUN. Observations below never mutate the renderer. +fn camera_tir_source(samples: Option, seed: u32, intensity: f64) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut body = dielectric::tests::box_body(2.0); + for point in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + point.x = if point.x < 0.0 { 0.0 } else { 1.0 }; + } + let options = RaytraceOptions { + progressive: samples.map(|samples_per_pixel| job::CpuProgressiveOptions { samples_per_pixel, seed }), + dielectrics: vec![dielectric::tests::input(job::DielectricBoundary::ClosedBox)], + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera = crate::Camera { + target: Vec3::new(0.9, 0.37, 2.0), + yaw: std::f64::consts::FRAC_PI_2, + pitch: 0.8_f64.asin(), + roll: 0.0, + distance: 10.0, + fov: 1e-6, + ..Default::default() + }; + (dielectric::tests::scene(body), request, options) +} + +#[derive(Clone, Default)] +struct CameraTirEvidence { + started: bool, + first_entry: Option<(Vec3, Vec3, u16)>, + tir: bool, + transmitted_escape: bool, + truncated_top_hit: bool, + finite_scalar: f64, + physical_tail_bound: f64, +} + +/// Independent public-equation oracle, conditional on the REAL camera direction. +/// No dielectric::interface/attenuation/thin_sheet call or renderer state mutation. +fn camera_tir_oracle(ray: Ray) -> (f64, f64) { + let d = ray.direction(); + assert!((d.x - 0.6).abs() < 2e-6 && (d.z + 0.8).abs() < 2e-6 && d.y.abs() < 2e-6); + let enter = ray.origin() + d * ((2.0 - ray.origin().z) / d.z); + assert!((enter.x - 0.9).abs() < 2e-5 && (enter.y - 0.37).abs() < 2e-5); + let cosine = -d.z; + let tx = d.x / 1.5; + let ct = (1.0 - (1.0 - cosine * cosine) / 2.25).sqrt(); + assert!(2.25 * (1.0 - tx * tx) > 1.0, "glass-to-air SIDE incidence is beyond critical"); + // All possible jittered rays in this narrow public-camera cone retain one + // lateral TIR per horizontal crossing, with three escapes before depth8. + let q = 2.0 * tx / ct; + assert!((1.0..2.0).contains(&(enter.x + q))); + let bottom1 = 2.0 - enter.x - q; + assert!((-1.0..0.0).contains(&(bottom1 - q))); + let top2 = q - bottom1; + assert!((1.0..2.0).contains(&(top2 + q))); + let bottom3 = 2.0 - top2 - q; + assert!((-1.0..0.0).contains(&(bottom3 - q))); + // s/p Fresnel *power* from first principles, then the declared scalar + // unpolarized model's three-term geometric return series. Eta² cancels on + // each complete air/glass/air escape. Lossless unit exterior radiance has + // infinite-depth physical answer1; finite omission <=max(Rs,Rp)^3. + let rs = ((cosine - 1.5 * ct) / (cosine + 1.5 * ct)).powi(2); + let rp = ((1.5 * cosine - ct) / (1.5 * cosine + ct)).powi(2); + let f = (rs + rp) * 0.5; + let finite = f + (1.0 - f).powi(2) * (1.0 + f + f * f); + assert!((finite - (1.0 - (1.0 - f) * f.powi(3))).abs() < 16.0 * f64::EPSILON); + (finite, rs.max(rp).powi(3)) +} + +fn complete_camera_tir(scene: ProductScene, request: ImageRequest, options: RaytraceOptions) -> Vec { + assert_eq!(MAX_BOUNDARIES, 8, "this oracle is derived for the actual eight-event model"); + let count = options.progressive.map_or(1, |p| p.samples_per_pixel) as usize; + let intensity = options.environment.unwrap().intensity; + let progressive = options.progressive.is_some(); + let mut evidence = vec![CameraTirEvidence::default(); count]; + let mut final_linear = None; + let mut checkpoints = 0; + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + // Deliberately use the public task poll to completion. The only writes to + // task state are its own API calls, never injected rays/paths/media/cursors. + for _ in 0..2_000_000 { + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() as usize == count + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered as usize, samples as usize), (count, count)); + final_linear = Some(rgb); + } + let poll = if progressive { + task.step_with_previews(1).unwrap() + } else { + match task.step(1).unwrap() { + TaskPoll::Pending(p) => ImagePoll::Pending(p), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + } + }; + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + let ordinal = state.camera_sample.map_or(0, |identity| { + assert_eq!(identity.0, 0); + identity.1 as usize + }); + let seen = &mut evidence[ordinal]; + assert!(state.path.boundaries <= 8); + if !seen.started { + assert_eq!(state.path.boundaries, 0); + let (finite, tail) = camera_tir_oracle(state.path.ray); + seen.finite_scalar = finite; + seen.physical_tail_bound = tail; + seen.started = true; + } + if state.path.boundaries == 1 && state.path.medium == Some(0) && seen.first_entry.is_none() { + let d = state.path.ray.direction(); + assert!((d.x - 0.4).abs() < 2e-6 && (d.z + (0.84_f64).sqrt()).abs() < 2e-6); + assert!((state.path.segment_start.z - 2.0).abs() < 1e-12); + seen.first_entry = Some((d, state.path.throughput, state.paths)); + } + if state.path.boundaries == 2 && state.path.medium == Some(0) { + let (before, throughput, paths) = seen.first_entry.unwrap(); + let after = state.path.ray.direction(); + assert!((state.path.segment_start.x - 1.0).abs() < 1e-12, "real ray hit lateral face"); + assert!(2.25 * (1.0 - before.x * before.x) > 1.0); + assert!((after - Vec3::new(-before.x, before.y, before.z)).len() < 1e-12); + assert!((state.path.throughput - throughput).len() < 1e-12, "TIR retains all current branch power"); + assert_eq!(state.paths, paths + 1, "only reflected path was created at TIR"); + // The primary reflection is still waiting; TIR itself leaves no + // transmitted child in addition to this resumed internal path. + assert_eq!(state.stack_len, 1); + seen.tir = true; + } + if state.path.boundaries == 3 && state.path.medium.is_none() { + assert!(seen.tir); + assert!(state.path.segment_start.z.abs() < 1e-12, "TIR branch really escaped through bottom"); + assert!(state.path.ray.direction().z < 0.0 && state.path.ray.direction().x < 0.0); + seen.transmitted_escape = true; + } + if state.path.boundaries == 8 + && state.path.medium == Some(0) + && let Some(hit) = task.pending.as_ref().and_then(|p| p.hit) + { + let vertices = task.looks[hit.primitive_index].vertices; + if vertices.iter().all(|v| v.z == 2.0) { + seen.truncated_top_hit = true; + } + } + } + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { .. } => { + assert!(task.optical.first().unwrap().pending.is_none()); + checkpoints += 1; + } + ImagePoll::Complete(png) => { + assert!(evidence.iter().all(|s| s.started && s.tir && s.transmitted_escape && s.truncated_top_hit)); + if progressive { + assert!(checkpoints > 0); + let expected = intensity * evidence.iter().map(|s| s.finite_scalar).sum::() / count as f64; + let omitted_bound = intensity * evidence.iter().map(|s| s.physical_tail_bound).sum::() / count as f64; + // Preselected absolute roundoff allowance, independent of + // product output. This is no numerical-certification claim. + let roundoff = 4096.0 * f64::EPSILON; + for actual in final_linear.unwrap() { + assert!((actual - expected).abs() <= roundoff, "independent finite scalar Fresnel series"); + assert!(actual <= intensity + roundoff); + assert!(actual >= intensity - omitted_bound - roundoff, "physical lossless energy with explicit finite-depth omission bound"); + } + if intensity == 1.0 { + assert!(expected < 1.0, "eight-event truncation is NOT perfect conservation"); + assert!(omitted_bound > 1e-5 && omitted_bound < 1e-3); + } + } + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + let expected = if intensity == 0.0 { [0, 0, 0, 255] } else { [188, 188, 188, 255] }; + assert_eq!(image.get_pixel(0, 0).0, expected, "black/white secondary environment controls, covered pixel"); + return png; + } + } + } + panic!("public-camera TIR fixture failed to produce complete image"); +} + +#[test] +fn camera_originated_tir_survives_fixed_render_to_final_png_with_environment_controls() { + let mut outputs = Vec::new(); + for intensity in [0.0, 1.0] { + let (scene, request, options) = camera_tir_source(None, 0, intensity); + outputs.push(complete_camera_tir(scene, request, options)); + } + assert_ne!(outputs[0], outputs[1]); +} + +#[test] +fn camera_originated_tir_progressive_final_obeys_physical_energy_and_explicit_depth_tail() { + for seed in [0, 97] { + for intensity in [0.0, 1.0] { + let (scene, request, options) = camera_tir_source(Some(5), seed, intensity); + let _ = complete_camera_tir(scene, request, options); + } + } +} + +#[test] +fn exposure_full_range_fixed_spatial_and_progressive_keep_linear_film_and_one_display_gain() { + // For +17/+32, reciprocal binary source radiance exposes to [1,1/2,1/4]. + // Reinhard gives [1/2,1/3,1/5]; IEC sRGB8 rounds to [188,156,124]. + // These are preselected mathematical values, not captures from the renderer. + for (ev, unit, expected) in [ + (-32.0, 1.0, [0, 0, 0, 255]), + (-17.0, 1.0, [0, 0, 0, 255]), + (0.0, 1.0, [188, 156, 124, 255]), + (17.0, 1.0 / 131_072.0, [188, 156, 124, 255]), + (32.0, 1.0 / 4_294_967_296.0, [188, 156, 124, 255]), + ] { + let color = [unit, unit * 0.5, unit * 0.25]; + for (progressive, primary_samples) in [(false, 1), (false, 4), (true, 1)] { + let (scene, mut request, mut options) = emission_fixture(false); + // Orthographic footprint x[-16,16],y[-8,8] fits inside both patches + // x[-20,0]/[0,20],y[-10,10] for every real pixel jitter. + request.camera.distance = 20.0; + options.exposure_ev = ev; + options.primary_samples = primary_samples; + options.progressive = progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 919 }); + options.emissions.as_mut().unwrap()[0].color = color; + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut observed_linear = false; + let mut completed = false; + for _ in 0..200_000 { + if let Some(state) = &task.progressive + && state.film.ready() + && state.film.samples() == 3 + { + let (rgb, covered, count) = state.film.pixel(0).unwrap(); + assert_eq!((covered, count), (3, 3)); + assert_eq!(rgb, color, "EV must not enter the accumulated linear film"); + let (dark, covered, count) = state.film.pixel(1).unwrap(); + assert_eq!((covered, count), (3, 3)); + assert_eq!(dark, [0.0; 3]); + observed_linear = true; + } + let poll = if progressive { + task.step_with_previews(1).unwrap() + } else { + match task.step(1).unwrap() { + TaskPoll::Pending(progress) => ImagePoll::Pending(progress), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + } + }; + let (png, final_frame) = match poll { + ImagePoll::Pending(_) => continue, + ImagePoll::Preview { png, .. } => { + assert!(progressive); + (png, false) + } + ImagePoll::Complete(png) => (png, true), + }; + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, expected, "EV={ev}, progressive={progressive}, spatial={primary_samples}"); + assert_eq!(image.get_pixel(1, 0).0, [0, 0, 0, 255]); + if final_frame { + completed = true; + break; + } + } + assert!(completed, "real public producer must finish its bounded fixture"); + assert!(!progressive || observed_linear); + } + } +} + +// Experimental strict core successor. Original public-camera fixtures; no +// injected ray, direction, medium, hit or stack creates the TIR sequences. +fn long_tir_source(width: f64, absorber: bool, progressive: bool, sigma: [f64; 3]) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut body = dielectric::tests::box_body(2.0); + for p in &mut std::sync::Arc::make_mut(&mut body.mesh).positions { + p.x = if p.x < 0.0 { 0.0 } else { width }; + } + let mut scene = dielectric::tests::scene(body); + if absorber { + assert_eq!(width, 0.05); + let xb = 0.875 - 4.0 / 21.0_f64.sqrt(); + let xr = xb - 0.001 * 0.4 / 0.84_f64.sqrt(); + assert!(xr > 0.0001 && xr + 0.0001 < width); + scene.meshes.push(crate::ProductMesh { + transmission: None, + name: "Original return absorber".into(), + mesh: std::sync::Arc::new(solidcraft_geom::Mesh { + positions: vec![ + Vec3::new(xr - 0.0001, -0.5, 0.001), + Vec3::new(xr + 0.0001, -0.5, 0.001), + Vec3::new(xr + 0.0001, 1.5, 0.001), + Vec3::new(xr - 0.0001, 1.5, 0.001), + ], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }); + } + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |a, m| a.union(&m.mesh.bounds())); + let mut medium = dielectric::tests::input(job::DielectricBoundary::ClosedBox); + medium.absorption_per_mm = sigma; + let options = RaytraceOptions { + dielectrics: vec![medium], + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + progressive: progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 71 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera = crate::Camera { + target: Vec3::new(width * 0.5, 0.37, 2.0), + yaw: std::f64::consts::FRAC_PI_2, + pitch: 0.8_f64.asin(), + roll: 0.0, + distance: 10.0, + fov: 1e-9, + ..Default::default() + }; + (scene, request, options) +} + +fn long_tir_expected(ray: Ray, sigma: [f64; 3], strict: bool) -> [f64; 3] { + let c = -ray.direction().z; + assert!((c - 0.8).abs() < 2e-9); + let ct = (1.0 - (1.0 - c * c) / 2.25).sqrt(); + let rs = ((c - 1.5 * ct) / (c + 1.5 * ct)).powi(2); + let rp = ((1.5 * c - ct) / (1.5 * c + ct)).powi(2); + let f = (rs + rp) * 0.5; + if strict { sigma.map(|s| f + (1.0 - f).powi(2) * (-s * 2.0 / ct).exp()) } else { [f; 3] } +} + +fn complete_long_tir(mut task: ImageTask, sigma: [f64; 3], strict: bool) -> Vec { + let count = task.visibility_owner.options().progressive.map_or(1, |p| p.samples_per_pixel) as usize; + let progressive = task.visibility_owner.options().progressive.is_some(); + let mut oracle = vec![None; count]; + let mut previous_tir = 0; + let mut previous_direction = vec![None; count]; + let mut actual_tir_rays = 0; + let mut escaped = vec![false; count]; + let mut absorbed = vec![false; count]; + let mut maximum = 0; + let mut linear = None; + for _ in 0..2_000_000 { + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() as usize == count + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered as usize, samples as usize), (count, count)); + linear = Some(rgb); + } + let poll = task.step_with_previews(1).unwrap(); + if let Some(optical) = task.optical.first() + && let Some(state) = &optical.pending + { + let ordinal = state.camera_sample.map_or(0, |identity| identity.1 as usize); + maximum = maximum.max(state.path.boundaries); + if oracle[ordinal].is_none() { + assert_eq!(state.path.boundaries, 0); + oracle[ordinal] = Some(long_tir_expected(state.path.ray, sigma, strict)); + } + if state.path.boundaries == 1 && state.path.medium == Some(0) && previous_direction[ordinal].is_none() { + previous_direction[ordinal] = Some(state.path.ray.direction()); + } + if optical.tir_continuations > previous_tir { + assert!(strict); + assert_eq!(optical.tir_continuations, previous_tir + 1); + assert_eq!(state.path.boundaries, 1, "TIR is not another split"); + assert_eq!(state.paths, 3, "initial path and two first-interface children only"); + assert_eq!(state.stack_len, 1, "waiting primary reflection is preserved"); + let before = previous_direction[ordinal].unwrap(); + let after = state.path.ray.direction(); + assert!((after - Vec3::new(-before.x, before.y, before.z)).len() < 1e-12); + assert!(task.pending.as_ref().unwrap().hit.is_none(), "real new TraceCursor has no borrowed old hit"); + previous_direction[ordinal] = Some(after); + previous_tir = optical.tir_continuations; + actual_tir_rays += 1; + } + if strict && state.path.boundaries == 2 && state.path.medium.is_none() && state.path.segment_start.z.abs() < 1e-12 { + assert_eq!(actual_tir_rays, 17 * (ordinal + 1)); + escaped[ordinal] = true; + } + if strict + && let Some(hit) = task.pending.as_ref().and_then(|p| p.hit) + && task.looks[hit.primitive_index].body_index == 1 + { + assert!(escaped[ordinal]); + absorbed[ordinal] = true; + } + } + if let ImagePoll::Complete(png) = poll { + let mut expected = [0.0; 3]; + for value in oracle { + for (sum, v) in expected.iter_mut().zip(value.unwrap()) { + *sum += v / count as f64; + } + } + if progressive { + for (actual, expected) in linear.unwrap().into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-10); + } + } + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, straight_expected_pixel(expected)); + if strict { + assert!(escaped.into_iter().all(|v| v) && absorbed.into_iter().all(|v| v)); + assert_eq!(actual_tir_rays, 17 * count); + assert_eq!(maximum, 2); + } else { + assert!(escaped.into_iter().all(|v| !v)); + assert_eq!(maximum, 8, "pre-fix witness: entry and seven TIRs exhaust legacy events"); + assert_eq!(actual_tir_rays, 0, "legacy policy never enters the new core branch"); + } + return png; + } + } + panic!("long TIR original fixture did not complete"); +} + +#[test] +fn legacy_long_tir_counterexample_loses_the_first_real_transmitted_exit() { + // This explicitly witnesses the retained C15 limitation, not a new physical + // success oracle. Its derived F-only result is contrasted with the strict + // terminating fixture below. No old L8 assertion is edited. + let (scene, request, options) = long_tir_source(0.05, true, true, [0.0; 3]); + let task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert!(!task.optical.first().unwrap().deterministic_tir); + let _ = complete_long_tir(task, [0.0; 3], false); +} + +#[test] +fn strict_core_long_tir_fixed_and_progressive_reach_real_exit_and_real_absorber() { + for progressive in [false, true] { + let (scene, request, options) = long_tir_source(0.05, true, progressive, [0.0; 3]); + let task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + let _ = complete_long_tir(task, [0.0; 3], true); + } +} + +#[test] +fn strict_core_long_tir_keeps_beer_on_all_real_reflected_segments() { + for progressive in [false, true] { + let sigma = [0.1, 0.2, 0.0]; + let (scene, request, options) = long_tir_source(0.05, true, progressive, sigma); + let task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + let _ = complete_long_tir(task, sigma, true); + } +} + +#[test] +fn strict_core_tir_more_than511_real_continuations_still_use_bvh_work_and_cancellation() { + for cancel in [false, true] { + let (scene, request, options) = long_tir_source(0.0005, false, true, [0.0; 3]); + let mut task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + let mut observed = false; + for _ in 0..2_000_000 { + let before = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert!(task.work.used() - before <= 1); + if task.optical.first().unwrap().tir_continuations == 512 { + let state = task.optical.first().unwrap().pending.as_ref().unwrap(); + assert_eq!((state.path.boundaries, state.paths, state.stack_len), (1, 3, 1)); + assert!(task.work.used() > 1024, "all previous traversals AND interfaces were real work"); + let start = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert_eq!(task.work.used(), start + 1, "newest real cursor also starts traversal before the stop"); + assert_eq!(task.optical.first().unwrap().tir_continuations, 512); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = task.work.used(); + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(frontier.completed_passes, 0); + assert!(!task.done); + observed = true; + break; + } + } + assert!(observed, "511 branch-state allowance must not truncate a deterministic ray sequence"); + } +} + +#[test] +fn strict_core_positive_non_tir_depth_limit_is_explicit_instead_of_black_completion() { + let (scene, request, options) = long_tir_source(0.05, false, true, [0.0; 3]); + let mut task = ImageTask::new_with_deterministic_tir(scene, request, CancelToken::default(), options, false).unwrap(); + for _ in 0..2_000_000 { + match task.step_with_previews(1) { + Err(error) => { + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(error.message.contains("non-TIR branch-depth budget exhausted")); + let optical = task.optical.first().unwrap(); + assert!(optical.tir_continuations >= 17); + assert!(optical.pending.as_ref().unwrap().paths <= 511); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + return; + } + Ok(ImagePoll::Pending(_)) => {} + Ok(_) => panic!("positive unresolved split cannot be published as a successful black tail"), + } + } + panic!("strict unresolved split was not reported"); +} + +// ORIGINAL UNAPPLIED PROPOSAL for the existing raytrace/image_tests.rs module. +// SOURCE ONLY: UNFORMATTED / UNCOMPILED / UNRUN. No new production policy API. +// This witnesses LEGACY bias; it is NOT a strict-quality success expectation. + +fn rational_depth_source(progressive: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + let scene = dielectric::tests::scene(dielectric::tests::box_body(2.0)); + let mut medium = dielectric::tests::input(job::DielectricBoundary::ClosedBox); + medium.ior = 3.0; + medium.absorption_per_mm = [0.0; 3]; + let options = RaytraceOptions { + dielectrics: vec![medium], + lights: Some(Vec::new()), + shadows: false, + environment: Some(job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }), + progressive: progressive.then_some(job::CpuProgressiveOptions { samples_per_pixel: 3, seed: 71 }), + ..Default::default() + }; + let mut request = dielectric::tests::request(options.clone()); + request.camera.target = Vec3::new(0.23, 0.37, 1.0); + request.camera.distance = 10.0; + request.camera.fov = 0.0; + (scene, request, options) +} + +fn rational_depth_real_cut(task: &ImageTask) -> bool { + let Some(optical) = task.optical.first() else { return false }; + let Some(state) = &optical.pending else { return false }; + if state.path.boundaries == 0 { + assert!((state.path.ray.direction() + Vec3::Z).len() < 1e-14); + } + if state.path.boundaries != 8 || state.path.medium != Some(0) || task.pending.as_ref().and_then(|p| p.hit).is_none() { + return false; + } + // All observed states came from the actual public camera/consumer. + // Entry plus seven true Fresnel splits, with the primary reflection waiting. + assert_eq!(state.paths, 17); + assert_eq!(state.stack_len, 1); + let expected = 1.0 / 196_608.0; + for value in [state.path.throughput.x, state.path.throughput.y, state.path.throughput.z] { + assert!(value > 0.0 && (value - expected).abs() < 1e-14); + } + true +} + +#[test] +fn legacy_public_normal_ior_three_has_a_positive_rational_depth_tail_hidden_by_png() { + const LEGACY_LINEAR: f64 = 65_533.0 / 65_536.0; + const OMITTED: f64 = 3.0 / 65_536.0; + assert_eq!(1.0 - LEGACY_LINEAR, OMITTED); + assert!(OMITTED > 1e-10); + for progressive in [false, true] { + let (scene, request, options) = rational_depth_source(progressive); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut cut_observed = false; + let mut linear = None; + let mut completed = false; + for _ in 0..200_000 { + cut_observed |= rational_depth_real_cut(&task); + if let Some(p) = &task.progressive + && p.film.ready() + && p.film.samples() == 3 + { + let (rgb, covered, samples) = p.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (3, 3)); + linear = Some(rgb); + } + let before_work = task.work.used(); + let poll = if progressive { + task.step_with_previews(1).unwrap() + } else { + match task.step(1).unwrap() { + TaskPoll::Pending(p) => ImagePoll::Pending(p), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + } + }; + assert!(task.work.used() >= before_work, "no ordinary-work reset across paths/passes"); + match poll { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { .. } => { + assert!(progressive); + assert!(task.optical.first().unwrap().pending.is_none()); + } + ImagePoll::Complete(png) => { + assert!(cut_observed); + if progressive { + for value in linear.unwrap() { + assert!((value - LEGACY_LINEAR).abs() < 1e-10); + assert!((value - 1.0).abs() > OMITTED * 0.5); + } + } + // Both physical1 and legacy65533/65536 round to188 under + // the documented Reinhard/IEC transfer: NOT a quality proof. + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [188, 188, 188, 255]); + completed = true; + break; + } + } + } + assert!(completed, "bounded legacy witness did not complete"); + } +} + +#[test] +fn public_normal_ior_three_real_positive_tail_still_obeys_cancel_and_work_limit() { + for cancel in [false, true] { + let (scene, request, options) = rational_depth_source(true); + let token = CancelToken::default(); + let mut task = ImageTask::new(scene, request, token.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..200_000 { + if rational_depth_real_cut(&task) { + reached = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(reached, "real camera traversal must reach the unresolved positive tail"); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert_eq!(frontier.completed_passes, 0); + let used = task.work.used(); + assert!(used > 0); + if cancel { + token.cancel(); // Actual caller-held public cancellation token. + } else { + // Existing unit-test control, not a new public budget API and not + // an injected ray, medium, hit or optical path. + task.work.limit = used; + } + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used, "failed/cancelled debit cannot advance or refund work"); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + } +} + +// ORIGINAL UNAPPLIED acceptance for Worker2 policy index ee17a4bb. +// Intended for the EXISTING raytrace/image_tests.rs, after the original +// rational_depth_source / rational_depth_real_cut helpers from index1685daca. +// UNFORMATTED / UNCOMPILED / UNRUN. No cfg(test)-only policy selector is used. + +fn rational_public_strict_source(progressive: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + let (scene, mut request, mut options) = rational_depth_source(progressive); + options.dielectric_transport = job::CpuDielectricTransport::StrictTir; + request.raytrace = Some(options.clone()); + (scene, request, options) +} + +#[test] +fn public_strict_ior_three_positive_non_tir_tail_is_a_real_error_before_final_or_sample() { + for progressive in [false, true] { + let (scene, request, options) = rational_public_strict_source(progressive); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut failed = false; + for _ in 0..200_000 { + let before = task.work.used(); + let poll = if progressive { + task.step_with_previews(1) + } else { + task.step(1).map(|poll| match poll { + TaskPoll::Pending(p) => ImagePoll::Pending(p), + TaskPoll::Complete(png) => ImagePoll::Complete(png), + }) + }; + match poll { + Ok(ImagePoll::Pending(_)) => assert!(task.work.used() >= before), + Ok(_) => panic!("strict positive rational tail cannot become preview/final quality"), + Err(error) => { + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(error.message.contains("strict optical non-TIR branch-depth budget exhausted")); + assert!(rational_depth_real_cut(&task), "actual depth8/paths17/positive internal state must exist"); + assert_eq!(task.work.used(), before + 1, "the real failing interface consumes its original tick"); + if progressive { + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap().completed_passes, 0); + } + assert!(!task.done); + failed = true; + break; + } + } + } + assert!(failed, "the actual selected strict policy must report its optical limit"); + } +} + +#[test] +fn public_strict_rational_tail_preserves_real_cancel_and_ordinary_work_accounting() { + for cancel in [false, true] { + let (scene, request, options) = rational_public_strict_source(true); + let token = CancelToken::default(); + let mut task = ImageTask::new(scene, request, token.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..200_000 { + if rational_depth_real_cut(&task) { + reached = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(reached); + let before = task.work.used(); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert_eq!(frontier.completed_passes, 0); + if cancel { + token.cancel(); + } else { + // Explicit established unit-test stop control, not a public option + // or a manufactured ray/hit/medium/branch. + task.work.limit = before; + } + let error = task.step_with_previews(1).err().unwrap(); + assert_eq!(error.code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(!task.done); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_public_final_strict_rational_tail_fails_without_a_frame_or_policy_fallback() { + use std::time::Duration; + let host = job::CpuHost::for_platform().unwrap(); + assert_eq!(host.kind(), job::HostKind::NativeWorker); + host.validate_integrator(job::Integrator::Raytrace).unwrap(); + // Exactly ONE required native branch marker; an unsupported configuration + // must fail rather than return early or switch to cooperative Raster. + eprintln!("STRICT_RATIONAL_BRANCH cpu_supported=true"); + for (index, progressive) in [false, true].into_iter().enumerate() { + let (scene, request, options) = rational_public_strict_source(progressive); + host.admit(&scene, &request, job::JobOptions::default()).unwrap(); + let id = job::JobId { session: 17361, serial: index as u64 + 1, generation: 1 }; + let handle = host.submit(id, 1, scene, request).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, job::Phase::Failed); + assert_eq!(status.request.raytrace.as_ref(), Some(&options)); + let error = status.error.as_ref().unwrap(); + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(error.message.contains("strict optical non-TIR branch-depth budget exhausted")); + assert!(handle.frame().unwrap().is_none()); + assert!(handle.preview().unwrap().is_none()); + } + // No immediate zero-pool claim: native terminal publication alone does not + // prove concurrent task/lease destruction has finished. +} + +mod original_directional_acceptance { + // Adopted W2 acceptance helpers; SOURCE ONLY / UNCOMPILED / UNRUN. + // Intended as a cfg(test) child module of raytrace::image, NOT as a crate or framework. + // Readonly OWNER getters and the real runtime flag are adapted explicitly below. + // Original donor8527 and oracle4ab12 stay sealed; registered cases follow these helpers. + use super::*; + use solidcraft_geom::{Aabb3, Mesh}; + use std::sync::Arc; + + const ORIGINAL_LINEAR: [[f64; 3]; 3] = [[0.8, 0.5, 0.25], [0.4, 0.125, 0.25], [0.2, 0.03125, 0.25]]; + const ORIGINAL_ABSOLUTE_TOLERANCE: f64 = 1e-12; + + fn original_receiver() -> crate::ProductMesh { + crate::ProductMesh { + transmission: None, + name: "Original directional receiver".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-4.0, -4.0, 0.0), Vec3::new(4.0, -4.0, 0.0), Vec3::new(4.0, 4.0, 0.0), Vec3::new(-4.0, 4.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + // IOR1 removes the normal-incidence interface term. Rough Lambert albedo + // and all original expected values were fixed before any consumer exists. + surface: Some(OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()), + faces: Vec::new(), + } + } + + fn original_box(ordinal: usize) -> crate::ProductMesh { + assert!(ordinal < 2); + let lo = if ordinal == 0 { 1.0 } else { 3.0 }; + let hi = lo + 1.0; + crate::ProductMesh { + transmission: None, + name: format!("Original directional glass {ordinal}"), + mesh: Arc::new(Mesh { + positions: (0..8) + .map(|i| Vec3::new(if i & 1 == 0 { -2.0 } else { 2.0 }, if i & 2 == 0 { -2.0 } else { 2.0 }, if i & 4 == 0 { lo } else { hi })) + .collect(), + // Outward winding of six closed rectangular faces, two triangles each. + triangles: vec![ + [0, 2, 3], + [0, 3, 1], + [4, 5, 7], + [4, 7, 6], + [0, 4, 6], + [0, 6, 2], + [1, 3, 7], + [1, 7, 5], + [0, 1, 5], + [0, 5, 4], + [2, 6, 7], + [2, 7, 3], + ], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + } + } + + /// Creates real scene/request/options with original admission. No flag or shadow mock. + /// Identity effect is a SEPARATE one-box case, not a replacement for the plain case. + pub(super) fn original_directional_fixture(boxes: usize, identity_effect: bool) -> (ProductScene, ImageRequest, RaytraceOptions) { + assert!(boxes <= 2); + assert!(!identity_effect || boxes == 1); + let mut meshes = vec![original_receiver()]; + let mut dielectrics = Vec::with_capacity(boxes); + for ordinal in 0..boxes { + let body = original_box(ordinal); + dielectrics.push(job::DielectricOptions { + body_index: meshes.len(), + body_name: body.name.clone(), + boundary: job::DielectricBoundary::ClosedBox, + ior: 1.0, + absorption_per_mm: [std::f64::consts::LN_2, 2.0 * std::f64::consts::LN_2, 0.0], + thickness_mm: 0.0, + }); + meshes.push(body); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |a, b| a.union(&b.mesh.bounds())); + let options = RaytraceOptions { + budget: job::CpuBudget::Compact, + primary_samples: 1, + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 1, seed: 81 }), + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: std::f64::consts::PI }]), + shadows: true, + exposure_ev: 0.0, + dielectrics, + surface_effects: identity_effect.then(|| { + vec![crate::surface_patterns::SurfaceEffect { + body: "Original directional receiver".into(), + frame: Default::default(), + repeat_mm: [10.0; 3], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }] + }), + ..Default::default() + }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + 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(options.clone()), + camera: crate::Camera { + target: Vec3::new(0.25, 0.37, 0.0), + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + roll: 0.0, + distance: 0.5, + // Perspective avoids the orthographic 3*distance origin translation. + // Tiny positive FOV keeps every real jittered ray essentially normal. + fov: 1e-9, + ..Default::default() + }, + width: 1, + height: 1, + background: [0; 3], + transparent_background: false, + }; + (ProductScene { meshes, bounds }, request, options) + } + + /// Real constructor/certifier and generated ray, with no skipped admission. + /// Selects the real mode for N1/N2; N0 deliberately retains the legacy/default route. + pub(super) fn original_directional_task(boxes: usize, identity_effect: bool) -> ImageTask { + let (scene, mut request, mut options) = original_directional_fixture(boxes, identity_effect); + options.directional_shadow_transmission = boxes != 0; + request.raytrace = Some(options.clone()); + options.validate().unwrap(); + for input in &options.dielectrics { + assert_ne!(input.body_index, 0, "receiver must remain optically unselected"); + assert_eq!(input.body_name, scene.meshes[input.body_index].name); + assert!(matches!(dielectric::certify(&scene, input).unwrap(), Certificate::ClosedBox(_))); + } + if identity_effect { + assert!(options.surface_effects.as_ref().unwrap()[0].prepare().unwrap().is_identity()); + } + admit(&scene, &request, &options).unwrap(); + let task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert_eq!(task.optical.len(), usize::from(boxes != 0)); + if identity_effect { + assert!(task.visibility_owner.options().surface_effects.is_some()); + assert!(task.effects.is_empty(), "identity is validated but not retained"); + } + let [dx, dy] = progressive::variates(81, 0, 0, 0); + let ray = primary_ray(&task.request, dx, dy, task.clip).unwrap(); + assert_original_primary(ray); + // Check the actual clipped generator at every pixel-corner bound as well. + for (x, y) in [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)] { + assert_original_primary(primary_ray(&task.request, x, y, task.clip).unwrap()); + } + task + } + + fn assert_original_primary(ray: Ray) { + assert!(ray.origin().z > 0.0 && ray.origin().z < 1.0, "REAL clipped primary origin must be between receiver and first box"); + assert!(ray.direction().z < 0.0); + assert!((ray.direction() + Vec3::Z).len() < 1e-8); + let t = -ray.origin().z / ray.direction().z; + assert!(t > ray.interval()[0] && t < ray.interval()[1]); + let on_receiver = ray.at(t).unwrap(); + assert!(on_receiver.x.abs() < 1.0 && on_receiver.y.abs() < 1.0); + } + + /// Observe a REAL ImageTask supplied by the future, separately reviewed consumer. + /// No fake mode, private state injection, visibility override or expected-from-output. + /// The registered tests select the real mode and use progressive polling below. + /// The legacy one-box test separately retains the original opaque-shadow contract. + pub(super) fn assert_original_directional_linear(mut task: ImageTask, boxes: usize, identity_effect: bool, retained_effect: bool) -> [f64; 3] { + assert!(boxes <= 2 && (!identity_effect || boxes == 1)); + assert!(!retained_effect || (boxes == 1 && !identity_effect)); + if identity_effect { + assert!(task.visibility_owner.options().surface_effects.as_ref().unwrap()[0].prepare().unwrap().is_identity()); + assert!(task.effects.is_empty(), "identity is validated and deliberately pruned"); + } + if retained_effect { + assert!(!task.visibility_owner.options().surface_effects.as_ref().unwrap()[0].prepare().unwrap().is_identity()); + assert_eq!(task.effects.len(), 1, "nonidentity must reach the actual scanner"); + } + assert_eq!(task.visibility_owner.options().dielectrics.len(), boxes); + assert_eq!(task.visibility_owner.options().budget, job::CpuBudget::Compact); + assert_eq!(task.visibility_owner.options().primary_samples, 1); + assert_eq!(task.visibility_owner.options().progressive.unwrap().seed, 81); + assert!(task.visibility_owner.options().environment.is_none()); + assert!(task.visibility_owner.options().emissions.is_none()); + assert!(task.visibility_owner.options().reflections.is_none()); + assert!(task.visibility_owner.options().punctual_lights.is_none()); + assert!(task.visibility_owner.options().area_lights.is_none()); + let lights = task.visibility_owner.options().lights.as_ref().unwrap(); + assert_eq!(lights.len(), 1); + assert_eq!(lights[0].direction, [0.0, 0.0, 1.0]); + assert_eq!(lights[0].color, [1.0; 3]); + assert_eq!(lights[0].intensity, std::f64::consts::PI); + assert_eq!(task.visibility_owner.source().meshes.len(), boxes + 1); + + assert_eq!(task.visibility_owner.options().progressive.unwrap().samples_per_pixel, 1); + // Exact observer contract: Legacy constructor, one SPP, no optional feedback. + // Legacy with more SPP CAN produce checkpoints; do not generalize this guard. + assert!(task.progressive.as_ref().unwrap().partial_plan.is_none()); + assert!(task.progressive.as_ref().unwrap().partial.is_none()); + assert!(task.work.protected.is_none()); + assert_eq!(task.visibility_owner.options().exposure_ev, 0.0); + assert!(task.visibility_owner.options().shadows); + assert_eq!((task.request.width, task.request.height), (1, 1)); + let mut saw_receiver = false; + let mut saw_unselected_optical = false; + let mut saw_retained_effect_scan = false; + let mut previous_work = task.work.used(); + for _ in 0..100_000 { + assert!(task.work.used() >= previous_work, "one cumulative ledger, no resets"); + previous_work = task.work.used(); + if let Some(pending) = task.pending.as_ref() { + assert_original_primary(pending.ray); + if let Some(hit) = pending.hit { + let scene = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: task.visibility_owner.source() }; + let shared = scene.resolve_hit(pending.ray, hit).unwrap(); + assert_eq!(shared.body_index, 0); + assert_eq!(shared.body_name, "Original directional receiver"); + assert!(shared.front_face); + assert!((shared.geometric_normal - Vec3::Z).len() < 1e-12); + // Exercise the actual geometric spawn helper, not a hand-offset ray. + let shadow = shared.spawn(Vec3::Z).unwrap(); + assert_eq!(shadow.direction(), Vec3::Z); + assert!(shadow.origin().z > 0.0 && shadow.origin().z < 1.0); + let receiver = &task.visibility_owner.source().meshes[0].mesh; + for indices in &receiver.triangles { + let vertices = indices.map(|i| receiver.positions[i as usize]); + assert!(Triangle::new(vertices).unwrap().intersect(&shadow).is_none(), "self-hit must not hide the Beer shadow oracle"); + } + saw_receiver = true; + if let Some(state) = task.optical.first().and_then(|o| o.pending.as_ref()) { + if state.ready { + assert!(state.selected.is_none(), "nonempty optical selectors must miss receiver"); + assert_eq!(state.selector, task.visibility_owner.options().dielectrics.len()); + assert_eq!(state.path.boundaries, 0, "camera must not transmit through glass"); + assert!(state.path.medium.is_none()); + saw_unselected_optical = true; + } + } + if retained_effect && pending.surface_ready && pending.surface_index.is_some() { + assert_eq!(pending.surface_cursor, task.effects.len()); + let affected = resolved_surface_hit(&scene, pending, &task.effects).unwrap(); + assert_eq!(affected.surface.base_color(), Vec3::new(0.8, 0.5, 0.25)); + assert_eq!(affected.surface.dielectric_ior(), 1.0); + assert_eq!(affected.surface.metallic(), 0.0); + assert!(affected.surface.clear_coat().is_none()); + assert!(affected.surface.roughness() < 1.0); + assert_eq!(affected.shading_normal, Vec3::Z); + saw_retained_effect_scan = true; + } + } + } + if let Some(progressive) = &task.progressive { + if progressive.film.ready() && progressive.film.samples() == 1 { + assert!(task.encoder.is_none() && task.pixels.is_empty()); + assert_eq!(progressive.resolve_pixel, 0); + assert!(task.pending.is_none()); + assert!(task.optical.first().is_none_or(|o| o.pending.is_none())); + let (linear, covered, samples) = progressive.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (1, 1)); + assert!(saw_receiver); + assert!(boxes == 0 || saw_unselected_optical); + assert!(!retained_effect || saw_retained_effect_scan); + for (actual, expected) in linear.into_iter().zip(ORIGINAL_LINEAR[boxes]) { + assert!(actual.is_finite()); + assert!( + (actual - expected).abs() <= ORIGINAL_ABSOLUTE_TOLERANCE, + "linear film {actual} differs from original oracle {expected}" + ); + } + // Return before any PNG resolve/encoding. No display inversion. + return linear; + } + } + match task.step_with_previews(1).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { samples_per_pixel, .. } => { + panic!("unexpected checkpoint at {samples_per_pixel} SPP before observing original linear film"); + } + ImagePoll::Complete(_) => panic!("completed before observing original linear film"), + } + } + panic!("original tiny fixture exceeded its fixed observation bound"); + } + + /// Separate negative validation witness for the identity case. No shortcut injection. + pub(super) fn assert_original_identity_target_is_still_validated() { + let (scene, mut request, mut options) = original_directional_fixture(1, true); + options.surface_effects.as_mut().unwrap()[0].body = "Missing identity target".into(); + request.raytrace = Some(options.clone()); + assert!(admit(&scene, &request, &options).is_err()); + assert!(ImageTask::new(scene, request, CancelToken::default(), options).is_err()); + } + + /// Additional REAL retained-effect variant for the second shadow-start route. + /// It preserves the already fixed one-box oracle, because IOR1/metallic0 is exact + /// Lambert for EVERY admitted roughness in the current surface contract. + pub(super) fn original_directional_retained_effect_fixture() -> (ProductScene, ImageRequest, RaytraceOptions) { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + let effect = crate::surface_patterns::SurfaceEffect { + body: "Original directional receiver".into(), + frame: crate::surface_patterns::MappingFrame { + // At the receiver hit(.25,.37,0), all three phases are -PI. + // Nearby tiny-FOV jitter keeps the cosine field negative; roughness + // changes below1. No tint API, normal change or geometry change. + origin_mm: [0.75, 0.87, 0.5], + ..Default::default() + }, + repeat_mm: [1.0; 3], + roughness_amplitude: 0.1, + bump_amplitude_mm: 0.0, + }; + let prepared = effect.prepare().unwrap(); + assert!(!prepared.is_identity()); + let material = scene.meshes[0].surface.unwrap(); + let applied = prepared.apply(material, Vec3::Z, Vec3::Z, Vec3::new(0.25, 0.37, 0.0)).unwrap(); + assert!(applied.surface.roughness() < material.roughness()); + assert_eq!(applied.surface.base_color(), material.base_color()); + assert_eq!(applied.surface.metallic(), 0.0); + assert_eq!(applied.surface.dielectric_ior(), 1.0); + assert_eq!(applied.shading_normal, Vec3::Z); + options.surface_effects = Some(vec![effect]); + request.raytrace = Some(options.clone()); + admit(&scene, &request, &options).unwrap(); + (scene, request, options) + } + + /// Retained-effect construction selects the real directional runtime mode. + pub(super) fn original_directional_retained_effect_task() -> ImageTask { + let (scene, mut request, mut options) = original_directional_retained_effect_fixture(); + options.directional_shadow_transmission = true; + request.raytrace = Some(options.clone()); + for input in &options.dielectrics { + assert!(matches!(dielectric::certify(&scene, input).unwrap(), Certificate::ClosedBox(_))); + } + let task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + assert_eq!(task.effects.len(), 1); + assert_eq!(task.effects[0].0, 0); + assert_eq!(task.optical.len(), 1); + let [dx, dy] = progressive::variates(81, 0, 0, 0); + assert_original_primary(primary_ray(&task.request, dx, dy, task.clip).unwrap()); + task + } + + #[test] + fn directional_real_film_matches_original_zero_one_two_box_oracles() { + for boxes in 0..=2 { + assert_original_directional_linear(original_directional_task(boxes, false), boxes, false, false); + } + } + + #[test] + fn directional_identity_is_pruned_and_retained_roughness_exercises_scanner() { + assert_original_directional_linear(original_directional_task(1, true), 1, true, false); + assert_original_identity_target_is_still_validated(); + assert_original_directional_linear(original_directional_retained_effect_task(), 1, false, true); + } + + #[test] + fn directional_default_preserves_opaque_glass_shadow_in_linear_film() { + let (scene, request, options) = original_directional_fixture(1, false); + assert!(!options.directional_shadow_transmission); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + for _ in 0..100_000 { + if let Some(progressive) = &task.progressive { + if progressive.film.ready() && progressive.film.samples() == 1 { + assert_eq!(progressive.film.pixel(0).unwrap(), ([0.0; 3], 1, 1)); + return; + } + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + panic!("legacy opaque-shadow film was not observed"); + } + + #[test] + fn directional_scan_uses_one_tick_per_active_poll_and_keeps_fixed_storage() { + let mut task = original_directional_task(2, false); + let slot = task.pending.0.as_ptr(); + let admission = admit(task.visibility_owner.source(), &task.request, task.visibility_owner.options()).unwrap(); + assert_eq!(admission.estimated_total_bytes, task.admission.estimated_total_bytes); + assert!(admission.preparation_bytes >= PendingPixelSlot::required_bytes()); + assert!(std::mem::size_of::() <= 4096); + let mut active_polls = 0; + for _ in 0..100_000 { + if task.progressive.as_ref().is_some_and(|p| p.film.ready() && p.film.samples() == 1) { + assert!(active_polls > 0); + assert!(task.pending.is_none()); + return; + } + let active = task.pending.as_ref().is_some_and(|p| p.directional_active); + let used = task.work.used(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + if active { + active_polls += 1; + assert_eq!(task.work.used(), used + 1); + } + assert_eq!(task.pending.0.capacity(), 1); + assert_eq!(task.pending.0.as_ptr(), slot); + } + panic!("bounded directional scan never reached committed film"); + } + + #[test] + fn directional_cancellation_or_work_limit_cannot_commit_a_pending_connection() { + for cancel in [false, true] { + let mut task = original_directional_task(1, false); + let mut reached = false; + for _ in 0..100_000 { + if task.pending.as_ref().is_some_and(|p| p.directional_active) { + reached = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(reached); + let used = task.work.used(); + assert!(task.finish_sample(Vec3::ZERO).is_err()); + assert_eq!(task.work.used(), used); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(task.pixels.is_empty() && task.encoder.is_none() && !task.done); + } + } + + #[test] + fn directional_context_refusals_and_completed_release_preserve_contracts() { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + request.raytrace = Some(options.clone()); + assert!(admit_with_nested(&scene, &request, &options, true).is_err()); + let mut mismatch = request.clone(); + mismatch.raytrace.as_mut().unwrap().directional_shadow_transmission = false; + assert!(admit(&scene, &mismatch, &options).is_err()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let weak = Arc::downgrade(&task.visibility_owner.source().meshes[0].mesh); + let budget = task.visibility_owner.options().budget; + for _ in 0..100_000 { + if let ImagePoll::Complete(png) = task.step_with_previews(16384).unwrap() { + assert!(::image::load_from_memory(&png).is_ok()); + assert!(weak.upgrade().is_none()); + assert!(task.visibility_owner.source().meshes.is_empty()); + assert!(task.visibility_owner.options().dielectrics.is_empty()); + assert_eq!(task.visibility_owner.options().budget, budget); + assert!(task.visibility_owner.options().directional_shadow_transmission); + assert!(task.request.raytrace.is_none() && task.optical.is_empty()); + assert!(task.step_with_previews(1).is_err()); + return; + } + } + panic!("directional completion did not release capture"); + } + + #[test] + fn directional_direct_constructor_refuses_separate_hdr_input() { + use crate::lighting::{HdrSource, environment_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, 128, 128, 129]); + } + let hdr = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap(); + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + request.raytrace = Some(options.clone()); + let error = ImageTask::new_with_environment(scene, request, CancelToken::default(), options, Some(hdr)).err().unwrap(); + assert_eq!(error.code, ErrorCode::InvalidRequest); + assert_eq!(error.message, "directional shadow transmission does not support HDR environments"); + } + + // Added during static coverage review after the initial twelve tests/body. + // Expectations are authored from geometry/Lambert/Beer, never candidate output. + #[test] + fn directional_second_light_has_its_own_oblique_beer_connection() { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + options.lights.as_mut().unwrap().push(job::DirectionalLightOptions { + direction: [0.6, 0.0, 0.8], + color: [1.0; 3], + intensity: 1.25 * std::f64::consts::PI, + }); + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + // Both box faces are hit in their interiors: x=1 at z1, x=1.75 at z2. + // Lz=4/5 gives chord5/4; intensity5*PI/4 cancels the Lambert cosine. + let oblique = [2.0_f64.powf(-1.25), 4.0_f64.powf(-1.25), 1.0]; + let expected = [0.4 + 0.8 * oblique[0], 0.125 + 0.5 * oblique[1], 0.5]; + let mut saw_both = false; + for _ in 0..100_000 { + if let Some(pending) = task.pending.as_ref() { + if pending.directional_complete == 3 { + assert!(!pending.directional_active); + let first = pending.directional_transmittance[0]; + let second = pending.directional_transmittance[1]; + assert!((first - Vec3::new(0.5, 0.25, 1.0)).len() < 1e-12); + assert!((second - Vec3::new(oblique[0], oblique[1], oblique[2])).len() < 1e-12); + saw_both = true; + } + } + if let Some(progressive) = &task.progressive { + if progressive.film.ready() && progressive.film.samples() == 1 { + assert!(saw_both); + let (linear, covered, samples) = progressive.film.pixel(0).unwrap(); + assert_eq!((covered, samples), (1, 1)); + for (actual, expected) in linear.into_iter().zip(expected) { + assert!((actual - expected).abs() <= 1e-12); + } + return; + } + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + panic!("independent directional connections never reached film"); + } + + #[test] + fn directional_fixed_spatial_samples_encode_original_rational_radiance_once() { + for samples in [1, 4, 16] { + let (scene, mut request, mut options) = original_directional_fixture(1, false); + options.directional_shadow_transmission = true; + options.progressive = None; + options.primary_samples = samples; + request.raytrace = Some(options.clone()); + let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let mut completed = false; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = task.step(1).unwrap() { + // Original linear(.4,.125,.25) -> Reinhard(2/7,1/9,1/5). + // encode8 is the unchanged encoding function, not a transport oracle. + let pixel = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(pixel.get_pixel(0, 0).0, [encode8(2.0 / 7.0), encode8(1.0 / 9.0), encode8(1.0 / 5.0), 255]); + completed = true; + break; + } + } + assert!(completed); + } + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/primary_aa_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/primary_aa_tests.rs new file mode 100644 index 000000000..2d03814f3 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/primary_aa_tests.rs @@ -0,0 +1,2031 @@ +//! Spatial AA regressions: WRITTEN NOT RUN. No historical gate is transferred. +use super::*; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use crate::{ProductMesh, StandardView}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn progressive_fixture(samples: u32, seed: u32, left: Option, exposure: f64) -> ImageTask { + // Reuse the analytic half-plane camera/geometry, not fixed-AA output. + let fixed = fixture(1, 1, left); + let mut options = fixed.visibility_owner.options().clone(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed }); + options.exposure_ev = exposure; + let mut request = fixed.request.clone(); + request.raytrace = Some(options.clone()); + ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() +} + +type ProgressiveOutput = (Vec<(u32, Vec)>, Vec, u64); +fn progressive_complete(mut task: ImageTask, quantum: usize) -> ProgressiveOutput { + let mut previews = Vec::new(); + for _ in 0..200_000 { + let result = task.step_with_previews(quantum).unwrap(); + let progress = task.progress(); + assert!(progress.done <= progress.total); + match result { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => previews.push((samples_per_pixel, png)), + ImagePoll::Complete(png) => return (previews, png, task.work.used()), + } + } + panic!("bounded progressive fixture did not finish"); +} + +#[test] +fn progressive_real_png_has_stable_prefixes_quanta_and_fresh_primary_samples() { + let (previews, final_png, work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 1); + assert_eq!(previews.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6, 7]); + let (other, other_final, other_work) = progressive_complete(progressive_fixture(8, 123, Some(true), 0.0), 16_384); + assert_eq!(other, previews); + assert_eq!(other_final, final_png); + assert_eq!(other_work, work, "quanta cannot reset or change the cumulative budget"); + for (samples, checkpoint) in &previews { + let (_, prefix, _) = progressive_complete(progressive_fixture(*samples, 123, Some(true), 0.0), 3); + assert_eq!(&prefix, checkpoint, "target SPP must not alter an earlier prefix"); + } + let mut task = progressive_fixture(8, 123, Some(true), 0.0); + let mut rays = Vec::new(); + for _ in 0..200_000 { + let absent = task.pending.is_none(); + let result = task.step_with_previews(1).unwrap(); + if absent && let Some(pending) = task.pending.as_ref() { + assert!(!pending.repeatable_primary, "jittered primary samples cannot use fixed-centre reuse"); + rays.push([pending.ray.origin().x.to_bits(), pending.ray.origin().y.to_bits()]); + } + if matches!(result, ImagePoll::Complete(_)) { + break; + } + } + assert_eq!(rays.len(), 8); + rays.sort(); + rays.dedup(); + assert_eq!(rays.len(), 8, "each absolute ordinal traces a new camera sample"); +} + +#[test] +fn progressive_coverage_keeps_backplate_outside_exposure_and_tone_mapping() { + for exposure in [-16.0, 0.0, 16.0] { + let (_, background, _) = progressive_complete(progressive_fixture(5, 9, None, exposure), 4); + assert_eq!(::image::load_from_memory(&background).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); + let (_, half, _) = progressive_complete(progressive_fixture(64, 9, Some(true), exposure), 4); + let covered = (0..64).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + assert!(covered > 0 && covered < 64); + let expected = encode8(1.0 - covered as f64 / 64.0); + assert_eq!(::image::load_from_memory(&half).unwrap().to_rgba8().get_pixel(0, 0).0, [expected, expected, expected, 255]); + } + let (previews, _, _) = progressive_complete(progressive_fixture(5, 9, Some(true), 0.0), 1); + assert_eq!( + previews.iter().map(|(samples, _)| *samples).collect::>(), + [1, 2, 3, 4], + "non-power-of-two target still has an exact final pass" + ); +} + +#[test] +fn progressive_resolves_the_mean_radiance_once_instead_of_averaging_display_pixels() { + let left = fixture(1, 1, Some(true)); + let right = fixture(1, 1, Some(false)); + let mut source = left.visibility_owner.source().clone(); + let mut other = right.visibility_owner.source().meshes[0].clone(); + other.name = "Bright half".into(); + source.bounds = source.bounds.union(&other.mesh.bounds()); + source.meshes.push(other); + let mut options = left.visibility_owner.options().clone(); + options.reflections = None; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 64, seed: 9 }); + options.exposure_ev = 1.0; + options.emissions = Some(vec![ + job::SurfaceEmission { body_index: 0, body: "Black half".into(), color: [1.0, 0.5, 0.25], strength: 1.0, sides: job::EmissionSides::Both }, + job::SurfaceEmission { body_index: 1, body: "Bright half".into(), color: [1.0, 0.5, 0.25], strength: 9.0, sides: job::EmissionSides::Both }, + ]); + let request = ImageRequest { raytrace: Some(options.clone()), ..left.request.clone() }; + let task = ImageTask::new(source, request, CancelToken::default(), options).unwrap(); + let (_, png, _) = progressive_complete(task, 4); + let left_count = (0..64).filter(|ordinal| progressive::variates(9, 0, *ordinal, 0)[0] < 0.5).count(); + let mean = (left_count as f64 + (64 - left_count) as f64 * 9.0) / 64.0; + let expected = [1.0, 0.5, 0.25].map(|color| { + let exposed = mean * color * 2.0; + encode8(exposed / (1.0 + exposed)) + }); + let actual = ::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0; + assert_eq!(actual, [expected[0], expected[1], expected[2], 255]); + let fraction = left_count as f64 / 64.0; + let prematurely_mapped = encode8(fraction * (2.0 / 3.0) + (1.0 - fraction) * (18.0 / 19.0)); + assert_ne!(actual[0], prematurely_mapped, "each sample must remain linear until the whole pass resolves"); +} + +#[test] +fn progressive_film_and_resolve_share_cancellation_and_one_cumulative_work_budget() { + let mut task = progressive_fixture(4, 0, Some(true), 0.0); + task.work = WorkBudget::new(1).unwrap(); + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + assert_eq!(task.step_with_previews(1).err().unwrap().code, ErrorCode::LimitExceeded); + for during_resolve in [false, true] { + let mut task = progressive_fixture(4, 0, Some(true), 0.0); + if during_resolve { + for _ in 0..200_000 { + if task.progressive.as_ref().is_some_and(|p| p.resolving) { + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(task.progressive.as_ref().unwrap().resolving); + } + task.cancel.cancel(); + assert_eq!(task.step_with_previews(4).err().unwrap().code, ErrorCode::Cancelled); + assert!(!task.done); + } +} + +fn fixture(samples: u8, r: u8, left: Option) -> ImageTask { + let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + let meshes = if let Some(left) = left { + let (x0, x1) = if left { (0.0, 0.5) } else { (0.5, 1.0) }; + let point = |x, y| { + let (o, _) = camera.ray(x, y, 1.0, 1.0); + Vec3::new(o.x, o.y, 0.0) + }; + vec![ProductMesh { + transmission: None, + name: "Black half".into(), + mesh: Arc::new(Mesh { + positions: vec![point(x0, 0.0), point(x1, 0.0), point(x1, 1.0), point(x0, 1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 1.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + }] + } else { + Vec::new() + }; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let options = RaytraceOptions { + primary_samples: samples, + lights: Some(Vec::new()), + shadows: false, + reflections: left.map(|_| ReflectionOptions { + bodies: vec![ReflectionBody { body: "Black half".into(), mode: ReflectionMode::RoughSpecular }], + samples: r, + max_bounces: 2, + }), + ..Default::default() + }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + 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(options.clone()), + camera, + width: 1, + height: 1, + background: [255; 3], + transparent_background: false, + }; + ImageTask::new(ProductScene { meshes, bounds }, request, CancelToken::default(), options).unwrap() +} +fn until_emit(task: &mut ImageTask) -> usize { + let mut primaries = 0; + let mut previous_primary = None; + for _ in 0..200_000 { + let absent = task.pending.is_none(); + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4); + if absent && task.pending.as_ref().is_some_and(|p| p.bounce == 0) { + primaries += 1; + let pending = task.pending.as_ref().unwrap(); + assert!(pending.repeatable_primary, "fixed generator must certify only intra-spatial R invariance"); + let o = pending.ray.origin(); + let d = pending.ray.direction(); + let ray = [o.x.to_bits(), o.y.to_bits(), o.z.to_bits(), d.x.to_bits(), d.y.to_bits(), d.z.to_bits()]; + if let Some((pixel, spatial, previous_ray)) = previous_primary { + if (pixel, spatial) == (task.pixel, task.spatial) { + assert_eq!(ray, previous_ray, "fixed primary ray changed between R attempts"); + } else { + assert_ne!(ray, previous_ray, "distinct spatial samples must not reuse their primary ray"); + } + } + previous_primary = Some((task.pixel, task.spatial, ray)); + } + if let Some(p) = task.pending.as_ref() { + if p.bounce != 0 { + assert!(!p.repeatable_primary, "secondary paths must revoke primary reuse"); + } else if let Some(hit) = p.hit { + let shared = PreparedScene { bvh: task.bvh.as_ref().unwrap(), primitives: &task.looks, source: task.visibility_owner.source() } + .resolve_hit(p.ray, hit) + .unwrap(); + if task.visibility_owner.options().reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|b| b.body == shared.body_name)) { + assert!(!p.repeatable_primary, "selected primary hit must revoke reuse even when its reflection is null"); + } + } + } + assert!(task.pixels.is_empty(), "early primary hit/miss emitted pixel"); + if task.progress().phase == Phase::Running { + assert_eq!(task.progress().done, 0, "subsamples counted as completed pixels"); + } + if task.emit_spatial_pixel { + return primaries; + } + } + panic!("bounded AA fixture did not reach emission"); +} +fn complete(mut task: ImageTask, quantum: usize) -> (Vec, u64) { + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(quantum).unwrap() { + return (png, task.work.used()); + } + } + panic!("bounded AA fixture did not finish"); +} + +#[test] +fn transient_options_are_strict_default_one_and_do_not_serialize_a_new_default_field() { + let omitted: RaytraceOptions = serde_json::from_str("{}").unwrap(); + let explicit: RaytraceOptions = serde_json::from_str(r#"{"primary_samples":1}"#).unwrap(); + assert_eq!(omitted, explicit); + assert_eq!(omitted.primary_samples, 1); + assert!(!serde_json::to_value(&omitted).unwrap().as_object().unwrap().contains_key("primary_samples")); + for n in [0, 2, 8, 17, 255] { + assert!(RaytraceOptions { primary_samples: n, ..Default::default() }.validate().is_err()); + } + for raw in [ + r#"{"primary_samples":-1}"#, + r#"{"primary_samples":1.5}"#, + r#"{"primary_samples":null}"#, + r#"{"primary_samples":"4"}"#, + r#"{"primary_samples":4,"unknown":0}"#, + ] { + assert!(serde_json::from_str::(raw).is_err()); + } +} + +#[test] +fn fixed_grids_have_independent_analytic_halfplane_and_triangle_coverage() { + assert_eq!(primary_offset(1, 0).unwrap(), [0.5, 0.5]); + assert_eq!(primary_offset(4, 0).unwrap(), [0.25, 0.25]); + assert_eq!(primary_offset(4, 3).unwrap(), [0.75, 0.75]); + for (s, half, triangle) in [(4, 2, 1), (16, 8, 3)] { + let points: Vec<_> = (0..s).map(|i| primary_offset(s, i).unwrap()).collect(); + assert!(points.iter().flatten().all(|v| *v > 0.0 && *v < 1.0)); + assert_eq!(points.iter().filter(|p| p[0] < 0.5).count(), half); + assert_eq!(points.iter().filter(|p| p[0] + p[1] < 5.0 / 8.0).count(), triangle); + assert!(primary_offset(s, s).is_err()); + } + assert!(primary_offset(8, 0).is_err()); + assert!(spatial_key(u64::MAX, 0, 16).is_err()); + assert_ne!(spatial_key(7, 0, 4).unwrap(), spatial_key(7, 1, 4).unwrap()); +} + +#[test] +fn compositor_keeps_conditional_scene_mean_then_display_linear_coverage() { + // White L=1, Reinhard=1/2; half coverage over black gives1/4 display-linear. + assert_eq!(composite_spatial(Vec3::new(0.5, 0.5, 0.5), 2, 4, [0; 3], 0.0).unwrap(), [encode8(0.25), encode8(0.25), encode8(0.25), 255]); + assert_ne!(encode8(0.25), encode8(1.0 / 3.0)); + // Full coverage of L=0 and L=2 usesT(mean)=1/2, not mean(T)=1/3. + assert_eq!(composite_spatial(Vec3::new(1.0, 1.0, 1.0), 4, 4, [255; 3], 0.0).unwrap(), [encode8(0.5), encode8(0.5), encode8(0.5), 255]); + for ev in [-16.0, 0.0, 16.0] { + assert_eq!(composite_spatial(Vec3::ZERO, 0, 16, [13, 27, 41], ev).unwrap(), [13, 27, 41, 255]); + } + let gray = srgb8_to_linear(128); + assert_eq!(composite_spatial(Vec3::ZERO, 2, 4, [128; 3], 0.0).unwrap(), [encode8(gray * 0.5), encode8(gray * 0.5), encode8(gray * 0.5), 255]); + assert!(composite_spatial(Vec3::ZERO, 5, 4, [0; 3], 0.0).is_err()); + assert!(composite_spatial(Vec3::X, 0, 4, [0; 3], 0.0).is_err()); +} + +#[test] +fn real_hit_first_and_miss_first_silhouettes_keep_all_attempts_and_null_coverage() { + for s in [4, 16] { + for r in [1, 4, 16, 64] { + for left in [false, true] { + let mut task = fixture(s, r, Some(left)); + let primaries = until_emit(&mut task); + assert_eq!(primaries, usize::from(s) * usize::from(r)); + assert_eq!(task.primary_coverage, u16::from(s) * u16::from(r) / 2); + let before = task.work.used(); + task.step(1).unwrap(); + assert_eq!(task.work.used(), before + 1); + assert_eq!(task.pixels, [encode8(0.5), encode8(0.5), encode8(0.5), 255]); + assert_eq!(task.pixel, 1); + } + } + } +} + +#[test] +fn miss_only_aa_retains_exact_background_and_quantum_independent_png() { + for s in [4, 16] { + let mut task = fixture(s, 1, None); + assert_eq!(until_emit(&mut task), usize::from(s)); + assert_eq!(task.primary_coverage, 0); + let small = complete(task, 1); + let large = complete(fixture(s, 1, None), 16384); + assert_eq!(small, large); + let image = ::image::load_from_memory(&small.0).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, [255; 4]); + } +} + +#[test] +fn spatial_finalization_and_emission_observe_shared_work_and_cancellation() { + for emit in [false, true] { + for cancel in [false, true] { + let mut task = fixture(16, 4, Some(false)); + for _ in 0..200_000 { + if (emit && task.emit_spatial_pixel) || (!emit && task.finish_spatial) { + break; + } + task.step(1).unwrap(); + } + assert!(if emit { task.emit_spatial_pixel } else { task.finish_spatial }); + let used = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + let code = task.step(1).err().unwrap().code; + assert_eq!(code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(!task.done && task.pixels.is_empty()); + } + } +} + +#[test] +fn legacy_single_primary_ignores_aa_state_and_preserves_default_bytes_work_and_order() { + for left in [None, Some(true), Some(false)] { + for r in [1, 4, 16, 64] { + let control = fixture(1, r, left); + let mut isolated = fixture(1, r, left); + isolated.spatial = 16; + isolated.primary_coverage = 1024; + isolated.spatial_radiance = Vec3::new(f64::NAN, 0.0, 0.0); + isolated.finish_spatial = true; + isolated.emit_spatial_pixel = true; + assert_eq!(complete(control, 1), complete(isolated, 16384)); + } + } + assert!(std::mem::size_of::() <= 4096); + assert_eq!(crate::raytrace::MAX_WORK, 1_000_000_000); + assert_eq!(job::image::MAX_JOB_BYTES, 384 * 1024 * 1024); + let legacy = fixture(1, 4, Some(false)); + let aa = fixture(16, 4, Some(false)); + assert_eq!(legacy.admission.estimated_total_bytes, aa.admission.estimated_total_bytes); +} + +#[test] +fn full_coverage_black_plane_never_leaks_display_background() { + for samples in [4, 16] { + let initial = fixture(samples, 16, Some(true)); + let top = initial.request.camera.ray(1.0, 0.0, 1.0, 1.0).0; + let bottom = initial.request.camera.ray(1.0, 1.0, 1.0, 1.0).0; + let (mut fixture_scene, fixture_options) = initial.visibility_owner.into_capture(); + let mesh = Arc::get_mut(&mut fixture_scene.meshes[0].mesh).unwrap(); + mesh.positions[1] = Vec3::new(top.x, top.y, 0.0); + mesh.positions[2] = Vec3::new(bottom.x, bottom.y, 0.0); + fixture_scene.bounds = mesh.bounds(); + let mut task = ImageTask::new(fixture_scene, initial.request, initial.cancel, fixture_options).unwrap(); + assert_eq!(until_emit(&mut task), usize::from(samples) * 16); + assert_eq!(task.primary_coverage, u16::from(samples) * 16); + task.step(1).unwrap(); + assert_eq!(task.pixels, [0, 0, 0, 255]); + } +} + +#[test] +fn later_spatial_attempts_do_not_reset_work_and_never_publish_when_interrupted() { + for cancel in [false, true] { + let mut task = fixture(16, 64, Some(true)); + for _ in 0..200_000 { + if task.spatial >= 1 && task.sample >= 1 { + break; + } + task.step(1).unwrap(); + } + assert!(task.spatial >= 1 && task.sample >= 1); + let used = task.work.used(); + assert!(used > 64, "no cumulative work across spatial samples"); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = used; + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), used); + assert!(!task.done && task.pixels.is_empty()); + } +} + +#[test] +fn actual_colored_lit_partial_coverage_wires_positive_radiance_exposure_and_background() { + for samples in [4, 16] { + for left in [false, true] { + let mut initial = fixture(samples, 1, Some(left)); + let (mut fixture_scene, mut fixture_options) = initial.visibility_owner.into_capture(); + fixture_scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()); + fixture_options.reflections = None; + fixture_options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }]); + fixture_options.exposure_ev = 1.0; + initial.request.background = [13, 73, 139]; + initial.request.raytrace = Some(fixture_options.clone()); + let mut task = ImageTask::new(fixture_scene, initial.request, initial.cancel, fixture_options).unwrap(); + assert_eq!(until_emit(&mut task), usize::from(samples)); + assert_eq!(task.primary_coverage, u16::from(samples) / 2); + // At normal incidence, unit-alpha white conductor: D=1/pi, + // G1=F=1, f=1/(4pi), incoming radiance=2*colored light. + let linear = [0.5, 1.0, 2.0].map(|v| v / (4.0 * std::f64::consts::PI)); + let expected_p = Vec3::new(linear[0], linear[1], linear[2]) * 0.5; + assert!((task.spatial_radiance - expected_p).len() < 1e-12); + let expected: [u8; 3] = std::array::from_fn(|i| { + let exposed = linear[i] * 2.0; + let display = 0.5 * exposed / (1.0 + exposed) + 0.5 * srgb8_to_linear([13, 73, 139][i]); + encode8(display) + }); + task.step(1).unwrap(); + assert_eq!(task.pixels, [expected[0], expected[1], expected[2], 255]); + } + } +} + +#[test] +fn workstation_progressive_streams_every_historical_2048_4096_checkpoint_and_checks_the_new_cap() { + let fixed = fixture(1, 1, Some(true)); + let cap = job::CpuBudget::Workstation.limits().max_samples_per_pixel; + assert_eq!(cap, 1_048_576); + for samples in [2048, 4096] { + let mut options = fixed.visibility_owner.options().clone(); + options.budget = job::CpuBudget::Workstation; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }); + let request = ImageRequest { raytrace: Some(options.clone()), ..fixed.request.clone() }; + let mut task = ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + let mut observed = Vec::new(); + let mut complete = false; + for _ in 0..200_000 { + match task.step_with_previews(16_384).unwrap() { + ImagePoll::Pending(_) => {} + ImagePoll::Preview { png, samples_per_pixel } => { + observed.push(samples_per_pixel); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1, 1)); + } + ImagePoll::Complete(png) => { + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1, 1)); + complete = true; + break; + } + } + } + assert!(complete); + assert_eq!(observed, (1..samples).collect::>()); + } + assert_eq!(composite_spatial(Vec3::ZERO, 0, 4097, [0; 3], 0.0).unwrap(), [0, 0, 0, 255]); + assert!(composite_spatial(Vec3::ZERO, 0, 1_048_577, [0; 3], 0.0).is_err()); +} + +#[test] +fn area_light_points_include_spatial_and_film_sample_identity() { + let light = super::super::area::RectangleLight::new(Vec3::Z * 10.0, Vec3::X * 4.0, -Vec3::Y * 4.0, Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap(); + let mut keys = std::collections::BTreeSet::new(); + let mut points = std::collections::BTreeSet::new(); + for film in [0, 1, 1023, 2047, 4095] { + for spatial in 0..16 { + let key = area_sample_key(41, spatial, 16, film).unwrap(); + assert!(keys.insert(key)); + let point = light.sample(Vec3::ZERO, key, 2, 0, 4, 73).unwrap().unwrap().position(); + assert!(points.insert((point.x.to_bits(), point.y.to_bits()))); + assert_eq!(light.sample(Vec3::ZERO, key, 2, 0, 4, 73).unwrap().unwrap().position(), point); + } + } + assert_eq!(area_sample_key(41, 0, 1, 0).unwrap(), 41); + assert_eq!(area_sample_key(41, 0, 1, 4096).unwrap(), (1_u64 << 63) | (41_u64 << 36) | (4096_u64 << 16)); + assert!(area_sample_key(41, 0, 1, 1_048_576).is_err()); + assert!(area_sample_key(41, 4, 4, 0).is_err()); + assert!(area_sample_key(u64::MAX, 0, 4, 0).is_err()); +} + +// Original receiver and rectangular source; no borrowed model or recorded image. +fn progressive_area_fixture(area_samples: u32, samples: u32, seed: u32, shadows: bool) -> ImageTask { + let original = fixture(1, 1, Some(true)); + let mut scene = original.visibility_owner.source().clone(); + scene.meshes[0].mesh = Arc::new(Mesh { + positions: vec![Vec3::new(-100.0, -100.0, 0.0), Vec3::new(100.0, -100.0, 0.0), Vec3::new(100.0, 100.0, 0.0), Vec3::new(-100.0, 100.0, 0.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap()); + scene.bounds = scene.meshes[0].mesh.bounds(); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed: 97 }), + lights: Some(Vec::new()), + area_lights: Some(vec![job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]), + area_samples: Some(area_samples), + seed: Some(seed), + shadows, + ..Default::default() + }; + let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} + +fn progressive_area_rebuild(source: &ImageTask, options: RaytraceOptions) -> ImageTask { + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + ImageTask::new(source.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() +} + +#[test] +fn progressive_area_transport_uses_absolute_film_ordinal_and_seed_for_all_sample_counts() { + use super::super::area::RectangleLight; + for count in [1, 4, 16, 64] { + for seed in [7, 91] { + let mut task = progressive_area_fixture(count, 2, seed, false); + let light = RectangleLight::new(Vec3::Z * 10.0, Vec3::X * 2.0, -Vec3::Y * 2.0, Vec3::new(1.0, 0.5, 0.25), 2.0).unwrap(); + let mut inspected = 0; + let mut first_positions = Vec::new(); + let mut complete = false; + for _ in 0..200_000 { + let ordinal = task.progressive.as_ref().unwrap().film.samples(); + let before = + task.pending.as_ref().filter(|p| p.hit.is_some() && p.area_light == 0 && p.area_index < count).map(|p| (p.area_index, p.ray)); + let poll = task.step_with_previews(1).unwrap(); + if let Some((index, ray)) = before + && let Some(pending) = task.pending.as_ref() + && pending.area_light == 0 + && pending.area_index == index + 1 + { + let point = ray.origin() + ray.direction() * (-ray.origin().z / ray.direction().z); + let key = area_sample_key(0, 0, 1, ordinal).unwrap(); + let sampled = light.sample(point, key, 0, index, count, seed).unwrap().unwrap(); + // Index-matched nonmetallic white receiver is exactly Lambertian. + // Check the actual consumer, independently of its BRDF and area weight. + let delta = sampled.position() - point; + let distance_squared = delta.dot(delta); + let factor = 4.0 * delta.z * delta.z / (distance_squared * distance_squared * f64::from(count) * std::f64::consts::PI); + let expected = Vec3::new(2.0, 1.0, 0.5) * factor; + assert!((pending.area_value - expected).len() < 1e-12, "N={count}, seed={seed}, film={ordinal}, index={index}"); + if index == 0 { + first_positions.push(sampled.position()); + } + inspected += 1; + } + if matches!(poll, ImagePoll::Complete(_)) { + complete = true; + break; + } + } + assert!(complete); + assert_eq!(inspected, 2 * count); + assert_eq!(first_positions.len(), 2); + if count == 1 { + assert_eq!(first_positions[0], first_positions[1], "one sample intentionally stays at the emitter centre"); + } else { + assert_ne!(first_positions[0], first_positions[1], "later film passes must not reuse the first emitter point"); + } + } + } +} + +#[test] +fn progressive_area_center_sample_resolves_the_analytic_linear_mean_once() { + let task = progressive_area_fixture(1, 3, 7, false); + let camera = task.request.camera; + let mut sum = Vec3::ZERO; + for ordinal in 0..3 { + let [u, v] = progressive::variates(97, 0, ordinal, 0); + let (origin, direction) = camera.ray(u, v, 1.0, 1.0); + let point = origin + direction * (-origin.z / direction.z); + let delta = Vec3::Z * 10.0 - point; + let r2 = delta.dot(delta); + sum += Vec3::new(2.0, 1.0, 0.5) * (4.0 * delta.z * delta.z / (r2 * r2 * std::f64::consts::PI)); + } + let mean = sum / 3.0; + let expected = [mean.x, mean.y, mean.z].map(|value| encode8(value / (1.0 + value))); + let (_, png, _) = progressive_complete(task, 1); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [expected[0], expected[1], expected[2], 255]); +} + +#[test] +fn progressive_area_checkpoints_and_work_are_independent_of_target_and_quantum() { + for count in [1, 4, 16, 64] { + let small = progressive_complete(progressive_area_fixture(count, 5, 23, true), 1); + let large = progressive_complete(progressive_area_fixture(count, 5, 23, true), 16_384); + assert_eq!(small, large, "area continuation must share the same cumulative work across quanta"); + assert_eq!(small.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4]); + for (samples, checkpoint) in &small.0 { + let (_, final_png, _) = progressive_complete(progressive_area_fixture(count, *samples, 23, true), 3); + assert_eq!(&final_png, checkpoint); + } + } +} + +#[test] +fn progressive_led_lowering_keeps_rectangle_power_sampling_and_final_bytes() { + let strip = job::led_strip::LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 2.0, + width_mm: 2.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }; + for count in [1, 4, 16, 64] { + let direct = progressive_area_fixture(count, 3, 7, true); + let mut options = direct.visibility_owner.options().clone(); + options.area_lights = None; + options.area_samples = None; + options.seed = None; + strip.append_to(&mut options, count).unwrap(); + options.seed = direct.visibility_owner.options().seed; + assert_eq!(options, *direct.visibility_owner.options()); + let lowered = progressive_area_rebuild(&direct, options); + assert_eq!(progressive_complete(direct, 1), progressive_complete(lowered, 7)); + } +} + +#[test] +fn progressive_area_admission_bills_source_capacity_and_reuses_bounded_scratch() { + let source = progressive_area_fixture(1, 3, 7, true); + let mut empty = source.visibility_owner.options().clone(); + empty.area_lights = None; + empty.area_samples = None; + empty.seed = None; + let baseline = progressive_area_rebuild(&source, empty); + let slots = source.visibility_owner.options().area_lights.as_ref().unwrap().capacity(); + let bytes = (slots * std::mem::size_of::()) as u64; + assert_eq!(source.visibility_owner.options().retained_bytes().unwrap(), bytes); + assert_eq!(source.admission.estimated_total_bytes - baseline.admission.estimated_total_bytes, bytes); + assert_eq!(source.admission.preparation_bytes - baseline.admission.preparation_bytes, bytes); + for count in [4, 16, 64] { + let more = progressive_area_fixture(count, 3, 7, true); + assert_eq!( + more.admission.estimated_total_bytes, source.admission.estimated_total_bytes, + "area samples reuse the same continuation, not an N-sized buffer" + ); + } + let mut over = source.request.clone(); + over.width = 1025; + over.height = 1024; + assert_eq!(admit(source.visibility_owner.source(), &over, source.visibility_owner.options()).err().unwrap().code, ErrorCode::LimitExceeded); +} + +#[test] +fn progressive_area_shadow_cancellation_and_checkpoint_do_not_reset_work() { + let mut task = progressive_area_fixture(16, 3, 7, true); + let mut pending_shadow = false; + for _ in 0..200_000 { + if task.pending.as_ref().is_some_and(|p| p.area_shadow) { + pending_shadow = true; + break; + } + assert!(matches!(task.step_with_previews(1).unwrap(), ImagePoll::Pending(_))); + } + assert!(pending_shadow); + let used = task.work.used(); + task.cancel.cancel(); + assert_eq!(task.step_with_previews(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used(), used); + assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0); + assert!(!task.done); + + let mut reference = progressive_area_fixture(16, 3, 7, true); + let mut checkpoint_work = None; + for _ in 0..200_000 { + if let ImagePoll::Preview { samples_per_pixel, .. } = reference.step_with_previews(1).unwrap() { + assert_eq!(samples_per_pixel, 1); + checkpoint_work = Some(reference.work.used()); + break; + } + } + let limit = checkpoint_work.unwrap(); + let mut bounded = progressive_area_fixture(16, 3, 7, true); + bounded.work = WorkBudget::new(limit).unwrap(); + let mut observed_checkpoint = false; + for _ in 0..200_000 { + match bounded.step_with_previews(1) { + Ok(ImagePoll::Pending(_)) => {} + Ok(ImagePoll::Preview { samples_per_pixel, .. }) => { + assert!(!observed_checkpoint); + assert_eq!(samples_per_pixel, 1); + observed_checkpoint = true; + assert_eq!(bounded.work.used(), limit); + } + Ok(ImagePoll::Complete(_)) => panic!("work exhausted after the checkpoint must not publish a final"), + Err(error) => { + assert_eq!(error.code, ErrorCode::LimitExceeded); + assert!(observed_checkpoint); + assert_eq!(bounded.work.used(), limit); + assert!(!bounded.done); + return; + } + } + } + panic!("area work ceiling was reset or the fixture did not finish"); +} + +fn partial_four_pixel_source(samples: u32, seed: u32) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut camera = crate::Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + let body = |name: &str, x0: f64, x1: f64| { + let point = |x, y| { + let (origin, _) = camera.ray(x, y, 4.0, 1.0); + Vec3::new(origin.x, origin.y, 0.0) + }; + ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(Mesh { + positions: vec![point(x0, 0.0), point(x1, 0.0), point(x1, 1.0), point(x0, 1.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0; 2], + ..Default::default() + }), + color: [0; 3], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 1.0, 1.5).unwrap()), + faces: Vec::new(), + } + }; + let meshes = vec![body("Partial red", 0.0, 1.0), body("Partial black", 2.0, 3.0)]; + let bounds = meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds())); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: samples, seed }), + lights: Some(Vec::new()), + shadows: false, + emissions: Some(vec![job::SurfaceEmission { + body_index: 0, + body: "Partial red".into(), + color: [1.0, 0.0, 0.0], + strength: 2.0, + sides: job::EmissionSides::Both, + }]), + ..Default::default() + }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + 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(options.clone()), + camera, + width: 4, + height: 1, + background: [10, 20, 30], + transparent_background: false, + }; + (ProductScene { meshes, bounds }, request, options) +} + +fn partial_four_pixel_task(samples: u32, seed: u32, partial: bool) -> ImageTask { + let (scene, request, options) = partial_four_pixel_source(samples, seed); + if partial { + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + ImageTask::new_with_environment_and_nested_and_partial(scene, request, CancelToken::default(), options, None, false, plan).unwrap() + } else { + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() + } +} + +type PartialRayLog = Vec<(usize, u32, [u64; 6])>; +fn record_partial_primary(task: &ImageTask, was_empty: bool, log: &mut PartialRayLog) { + if was_empty && let Some(pending) = task.pending.as_ref() { + let origin = pending.ray.origin(); + let direction = pending.ray.direction(); + let ordinal = task.progressive.as_ref().unwrap().film.samples(); + log.push(( + task.pixel, + ordinal, + [origin.x.to_bits(), origin.y.to_bits(), origin.z.to_bits(), direction.x.to_bits(), direction.y.to_bits(), direction.z.to_bits()], + )); + } +} +fn reach_partial_frontier(task: &mut ImageTask, passes: u32, prefix: usize, rays: &mut PartialRayLog) { + for _ in 0..200_000 { + if let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.partial_frontier().unwrap().completed_passes == passes + && progressive.film.partial_frontier().unwrap().updated_prefix == prefix + && task.pending.is_none() + { + return; + } + let was_empty = task.pending.is_none(); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + record_partial_primary(task, was_empty, rays); + } + panic!("real task did not reach requested committed frontier"); +} +fn finish_partial_snapshot(task: &mut ImageTask) -> (Vec, Vec, u32, u64) { + let paid = task.work.used(); + for _ in 0..200_000 { + let poll = task.step_with_partial_previews(1).unwrap(); + assert_eq!(task.work.used(), paid, "prepaid resolve/encode must not debit the job twice"); + match poll { + PartialImagePoll::Pending(_) => {} + PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix } => return (png, covered, completed_passes, updated_prefix), + PartialImagePoll::Complete(_) => panic!("partial snapshot must not become a final frame"), + } + } + panic!("bounded partial snapshot did not finish"); +} +fn finish_partial_final(task: &mut ImageTask, partial: bool, rays: &mut PartialRayLog) -> (Vec, Vec<[u64; 3]>) { + let target = task.visibility_owner.options().progressive.unwrap().samples_per_pixel; + let mut bits = None; + for _ in 0..1_000_000 { + if bits.is_none() + && let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.samples() == target + { + bits = Some( + (0..task.request.width as usize * task.request.height as usize) + .map(|index| progressive.film.pixel(index).unwrap().0.map(f64::to_bits)) + .collect(), + ); + } + let was_empty = task.pending.is_none(); + let complete = if partial { + match task.step_with_partial_previews(1).unwrap() { + PartialImagePoll::Pending(_) => None, + PartialImagePoll::Complete(png) => Some(png), + PartialImagePoll::Preview { .. } => panic!("producer created an unrequested partial snapshot"), + } + } else { + match task.step_with_previews(1).unwrap() { + ImagePoll::Pending(_) | ImagePoll::Preview { .. } => None, + ImagePoll::Complete(png) => Some(png), + } + }; + record_partial_primary(task, was_empty, rays); + if let Some(png) = complete { + return (png, bits.expect("uniform target film must exist before final resolution")); + } + } + panic!("partial/control final did not finish"); +} + +#[test] +fn partial_real_film_png_distinguishes_unknown_miss_hit_and_known_black() { + let mut task = partial_four_pixel_task(5, 123, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + assert!(task.partial_preview_ready(plan).unwrap()); + let before = task.work.used(); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + assert_eq!(task.work.used(), before + plan.snapshot_work().unwrap()); + let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix, task.pixel), (0, 2, 2)); + assert_eq!(covered, [1, 0, 0, 0]); + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (4, 1)); + assert_eq!(image.get_pixel(0, 0).0, [213, 0, 0, 255], "linear red2 -> Reinhard2/3 -> sRGB213"); + assert_eq!(image.get_pixel(1, 0).0, [10, 20, 30, 255], "observed miss is the captured backplate"); + assert_eq!(image.get_pixel(2, 0).0, [0, 0, 0, 0]); + assert_eq!(image.get_pixel(3, 0).0, [0, 0, 0, 0]); + + reach_partial_frontier(&mut task, 1, 0, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix, task.pixel), (1, 0, 4), "snapshot retains the sentinel until the normal charged transition"); + assert_eq!(covered, [1, 0, 1, 0]); + let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(2, 0).0, [0, 0, 0, 255], "known black is opaque, not Unknown"); + assert_eq!(image.get_pixel(3, 0).0, [10, 20, 30, 255]); +} + +#[test] +fn partial_snapshots_preserve_interior_cursor_absolute_rays_and_final_bits() { + for seed in [0, 123] { + let mut task = partial_four_pixel_task(5, seed, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + let mut actual_rays = Vec::new(); + for (passes, prefix) in [(0, 1), (0, 3), (1, 0)] { + reach_partial_frontier(&mut task, passes, prefix, &mut actual_rays); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(task.pixel, if prefix == 0 { 4 } else { prefix }); + } + let actual = finish_partial_final(&mut task, true, &mut actual_rays); + let mut control = partial_four_pixel_task(5, seed, false); + let mut control_rays = Vec::new(); + let expected = finish_partial_final(&mut control, false, &mut control_rays); + assert_eq!(actual, expected, "final PNG and linear film bits must be exact"); + assert_eq!(actual_rays, control_rays, "snapshot timing cannot replay a camera pixel or ordinal"); + assert_eq!(actual_rays.len(), 20); + } +} + +#[test] +fn partial_work_preflight_is_optional_and_successful_debit_is_once() { + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + for enough in [false, true] { + let mut task = partial_four_pixel_task(5, 123, true); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let before = task.work.used(); + let cost = plan.snapshot_work().unwrap(); + task.work.limit = before + cost - u64::from(!enough); + if enough { + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + assert_eq!(task.work.used(), before + cost); + let _ = finish_partial_snapshot(&mut task); + assert_eq!( + task.step_with_partial_previews(1).err().unwrap().code, + ErrorCode::LimitExceeded, + "accepted presentation does not promise future trace headroom" + ); + } else { + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Exhausted)); + assert_eq!(task.work.used(), before); + assert_eq!(task.pixel, 2); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert!(task.progressive.as_ref().unwrap().partial.is_none()); + assert!(task.encoder.is_none() && task.pixels.is_empty()); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + } + } +} + +#[test] +fn partial_ready_requires_actual_safe_commit_plan_and_new_represented_state() { + let mut task = partial_four_pixel_task(5, 123, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + assert!(!task.partial_preview_ready(plan).unwrap()); + let mut observed_pending = false; + for _ in 0..200_000 { + let _ = task.step_with_partial_previews(1).unwrap(); + if !task.pending.is_none() { + assert!(!task.partial_preview_ready(plan).unwrap()); + let used = task.work.used(); + assert!(task.begin_partial_preview(plan).is_err()); + assert_eq!(task.work.used(), used); + observed_pending = true; + break; + } + } + assert!(observed_pending, "test must observe a real in-flight primary pixel"); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(task.partial_preview_ready(job::PartialPreviewPlan::new(8, 1).unwrap()).is_err()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert!(!task.partial_preview_ready(plan).unwrap(), "same frontier cannot be a fresh snapshot"); + + use crate::film::primary::PartialFrontier; + let reduced = job::PartialPreviewPlan::new(4096, 1).unwrap(); + let old = PartialFrontier { completed_passes: 0, updated_prefix: 1, pixels: 4096 }; + assert!(!progressive::represented_changed(reduced, Some(old), PartialFrontier { updated_prefix: 4, ..old }).unwrap()); + assert!(progressive::represented_changed(reduced, Some(old), PartialFrontier { updated_prefix: 5, ..old }).unwrap()); +} + +#[test] +fn partial_cancel_before_resolve_or_during_encoding_never_emits_payload() { + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + for during_encoding in [false, true] { + let mut task = partial_four_pixel_task(5, 123, true); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let paid = task.work.used(); + if during_encoding { + for _ in 0..20 { + if task.encoder.is_some() { + break; + } + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + } + assert!(task.encoder.is_some()); + } + task.cancel.cancel(); + assert_eq!(task.step_with_partial_previews(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used(), paid, "there is no refund or second partial-stage debit"); + assert!(!task.done); + } +} + +#[test] +fn partial_reduced_resolve_is_bounded_by_display_cells_and_admission_is_not_legacy_prepay() { + let fixed = fixture(1, 1, None); + let mut options = fixed.visibility_owner.options().clone(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 5, seed: 123 }); + let mut request = fixed.request.clone(); + request.width = 1500; + request.raytrace = Some(options.clone()); + let plan = job::PartialPreviewPlan::new(1500, 1).unwrap(); + let first = admit_with_partial_preview(fixed.visibility_owner.source(), &request, &options, false, plan).unwrap(); + options.progressive.as_mut().unwrap().samples_per_pixel = 9; + request.raytrace = Some(options.clone()); + let second = admit_with_partial_preview(fixed.visibility_owner.source(), &request, &options, false, plan).unwrap(); + assert_eq!(first.estimated_total_bytes, second.estimated_total_bytes, "streaming reserves two slots, not every legacy power2 image"); + let (fixture_scene, _) = fixed.visibility_owner.into_capture(); + let mut task = + ImageTask::new_with_environment_and_nested_and_partial(fixture_scene, request, CancelToken::default(), options, None, false, plan).unwrap(); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let paid = task.work.used(); + let mut output = None; + let mut steps = 0_u64; + for _ in 0..2000 { + steps += 1; + match task.step_with_partial_previews(1).unwrap() { + PartialImagePoll::Pending(_) => {} + PartialImagePoll::Preview { png, covered, .. } => { + output = Some((png, covered)); + break; + } + PartialImagePoll::Complete(_) => panic!("display resolve cannot complete the final"), + } + assert_eq!(task.work.used(), paid); + } + let (png, covered) = output.expect("bounded reduced snapshot"); + assert_eq!(steps, plan.pixels() + u64::from(plan.height()) + 2); + assert_eq!(covered.len() as u64, plan.pixels()); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1)); + assert_eq!((task.request.width, task.request.height), (1500, 1)); + assert_eq!(task.pixel, 1); +} + +#[test] +fn partial_area_first_pass_and_final_preserve_all_existing_emitter_sample_counts() { + for area_samples in [1, 4, 16, 64] { + let source = progressive_area_fixture(area_samples, 5, 23, true); + let plan = job::PartialPreviewPlan::new(source.request.width, source.request.height).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + None, + false, + plan, + ) + .unwrap(); + reach_partial_frontier(&mut task, 1, 0, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (first, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (1, 0)); + let (actual, _) = finish_partial_final(&mut task, true, &mut Vec::new()); + let (legacy_previews, expected, _) = progressive_complete(source, 1); + assert_eq!(first, legacy_previews[0].1); + assert_eq!(actual, expected, "area source normalization/sampler must remain unchanged"); + } +} + +fn partial_original_hdr() -> crate::lighting::environment_input::EnvironmentInput { + use crate::lighting::{HdrSource, environment_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, 128, 128, 129]); + } + EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 4).unwrap() +} + +#[test] +fn partial_hdr_rough_reflection_first_pass_and_final_match_legacy_sampling() { + let base = fixture(1, 1, Some(true)); + let mut scene = base.visibility_owner.source().clone(); + scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 1.0, 0.35, 1.5).unwrap()); + let mut options = base.visibility_owner.options().clone(); + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 5, seed: 23 }); + let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() }; + let plan = job::PartialPreviewPlan::new(request.width, request.height).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + Some(partial_original_hdr()), + false, + plan, + ) + .unwrap(); + let control = ImageTask::new_with_environment(scene, request, CancelToken::default(), options, Some(partial_original_hdr())).unwrap(); + reach_partial_frontier(&mut task, 1, 0, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (first, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (1, 0)); + let (actual, _) = finish_partial_final(&mut task, true, &mut Vec::new()); + let (legacy_previews, expected, _) = progressive_complete(control, 1); + assert_eq!(first, legacy_previews[0].1); + assert_eq!(actual, expected, "HDR and rough-reflection sample identity cannot depend on presentation"); +} + +#[test] +fn partial_full_pass_snapshot_preserves_regular_transition_work_and_final_ledger() { + let mut task = partial_four_pixel_task(5, 123, true); + let mut control = partial_four_pixel_task(5, 123, true); + let plan = job::PartialPreviewPlan::new(4, 1).unwrap(); + let mut actual_rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut actual_rays); + reach_partial_frontier(&mut control, 1, 0, &mut control_rays); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert_eq!(frontier, control.progressive.as_ref().unwrap().film.partial_frontier().unwrap()); + assert_eq!((task.pixel, control.pixel), (4, 4)); + let before = control.work.used(); + assert_eq!(task.work.used(), before); + let cost = plan.snapshot_work().unwrap(); + assert!(matches!(task.begin_partial_preview(plan).unwrap(), PartialBegin::Started)); + let (_, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix, task.pixel), (1, 0, 4), "snapshot may not consume the ordinary pass transition"); + assert_eq!(task.work.used(), before + cost); + assert_eq!(control.work.used(), before); + assert!(!task.partial_preview_ready(plan).unwrap(), "unchanged frontier remains coalesced"); + + // The host hashes without stepping this task. On the next producer step, + // BOTH tasks owe the same ordinary pass-transition debit before a new ray. + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert!(matches!(control.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert_eq!((task.pixel, control.pixel), (0, 0)); + assert!(task.pending.is_none() && control.pending.is_none()); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(control.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(control.work.used(), before + 1, "the no-snapshot control owes the regular transition tick"); + assert_eq!(task.work.used(), before + cost + 1, "the snapshot must preserve that same tick in addition to W"); + + let actual = finish_partial_final(&mut task, true, &mut actual_rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected, "same partial policy: final PNG and linear film bits are exact"); + assert_eq!(actual_rays, control_rays, "presentation cannot replay or skip a primary sample"); + assert_eq!(actual_rays.len(), 20); + assert_eq!(task.work.used(), control.work.used() + cost, "the complete-job optional cost is exactly W, not W-1"); +} + +fn protected_plan(task: &ImageTask) -> job::ProtectedPreviewPlan { + job::ProtectedPreviewPlan::new( + task.request.width, + task.request.height, + task.visibility_owner.options().progressive.unwrap().samples_per_pixel, + task.visibility_owner.options().budget, + ) + .unwrap() +} +fn protected_rebuild(source: &ImageTask, input: Option) -> ImageTask { + ImageTask::new_with_environment_and_nested_and_protected_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + input, + false, + protected_plan(source), + ) + .unwrap() +} +fn shared_partial_rebuild(source: &ImageTask, input: Option) -> ImageTask { + ImageTask::new_with_environment_and_nested_and_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + input, + false, + protected_plan(source).preview_plan(), + ) + .unwrap() +} +fn empty_progressive_source() -> ImageTask { + let fixed = fixture(1, 1, None); + let options = RaytraceOptions { + progressive: Some(job::CpuProgressiveOptions { samples_per_pixel: 64, seed: 123 }), + lights: Some(Vec::new()), + shadows: false, + ..Default::default() + }; + let request = ImageRequest { width: 32, height: 32, background: [10, 20, 30], raytrace: Some(options.clone()), ..fixed.request }; + let (fixture_scene, _) = fixed.visibility_owner.into_capture(); + ImageTask::new(fixture_scene, request, CancelToken::default(), options).unwrap() +} +fn initial_test_work(task: &mut ImageTask, ordinary: u64, protected: bool) { + assert_eq!(task.work.used(), 0, "test boundary is fixed BEFORE any real work, never mid-render"); + task.work = + if protected { WorkBudget::new_protected_for_test(protected_plan(task), ordinary).unwrap() } else { WorkBudget::new(ordinary).unwrap() }; +} +fn require_empty_final(png: &[u8], bits: &[[u64; 3]]) { + let image = ::image::load_from_memory(png).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (32, 32)); + assert!(image.pixels().all(|p| p.0 == [10, 20, 30, 255]), "independent all-miss backplate oracle"); + assert_eq!(bits.len(), 1024); + assert!(bits.iter().all(|p| *p == [0.0_f64.to_bits(); 3]), "no emitted or reflected radiance in the empty fixture"); +} + +#[test] +fn protected_actual_empty_counterexample_preserves_final_work_while_shared_cap_can_starve() { + let source = empty_progressive_source(); + let plan = protected_plan(&source); + assert_eq!((plan.total_commits(), plan.quota_limit(), plan.snapshot_work().unwrap()), (65536, 127, 79874)); + let mut reference = shared_partial_rebuild(&source, None); + let mut reference_rays = Vec::new(); + let expected = finish_partial_final(&mut reference, true, &mut reference_rays); + require_empty_final(&expected.0, &expected.1); + let ordinary = reference.work.used(); + assert!(ordinary > plan.snapshot_work().unwrap()); + + let mut control = shared_partial_rebuild(&source, None); + initial_test_work(&mut control, ordinary, false); + let actual = finish_partial_final(&mut control, true, &mut Vec::new()); + assert_eq!(actual, expected); + assert_eq!(control.work.used(), ordinary); + + let mut starved = shared_partial_rebuild(&source, None); + initial_test_work(&mut starved, ordinary, false); + reach_partial_frontier(&mut starved, 0, 1, &mut Vec::new()); + assert!(matches!(starved.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut starved); + let mut failure = None; + for _ in 0..1_000_000 { + match starved.step_with_partial_previews(1) { + Ok(PartialImagePoll::Pending(_)) => {} + Ok(PartialImagePoll::Complete(_)) => panic!("shared cap T cannot pay the same T ordinary work plus W"), + Ok(PartialImagePoll::Preview { .. }) => panic!("no unrequested snapshot"), + Err(error) => { + failure = Some(error.code); + break; + } + } + } + assert_eq!(failure, Some(ErrorCode::LimitExceeded)); + assert!(!starved.done); + assert!(starved.work.used() <= ordinary); + + for request_snapshot in [false, true] { + let mut task = protected_rebuild(&source, None); + initial_test_work(&mut task, ordinary, true); + let mut rays = Vec::new(); + if request_snapshot { + reach_partial_frontier(&mut task, 0, 1, &mut rays); + let before = task.protected_preview_report().unwrap(); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let paid = task.protected_preview_report().unwrap(); + assert_eq!(paid.ordinary_used, before.ordinary_used); + assert_eq!((paid.presentation_used, paid.accepted_snapshots), (79874, 1)); + } + let actual = finish_partial_final(&mut task, true, &mut rays); + assert_eq!(actual, expected, "protected feedback cannot change PNG or linear film"); + assert_eq!(rays, reference_rays, "absolute pixel/ordinal/ray sequence is identical"); + assert_eq!(rays.len(), 65536); + let report = task.protected_preview_report().expect("actual report survives completed-film destruction"); + assert_eq!(report.ordinary_used, ordinary); + let optional = if request_snapshot { 79874 } else { 0 }; + assert_eq!(report.presentation_used, optional); + assert_eq!(task.work.used(), ordinary + optional); + assert_eq!(report.aggregate_limit, ordinary + plan.presentation_limit().unwrap()); + assert!(task.done && task.progressive.is_none()); + } +} + +#[test] +fn protected_real_milestone_wait_is_not_exhaustion_or_a_debit() { + let source = empty_progressive_source(); + let mut task = protected_rebuild(&source, None); + let plan = protected_plan(&task); + let preview = plan.preview_plan(); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(preview).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + reach_partial_frontier(&mut task, 0, 2, &mut Vec::new()); + let before = task.protected_preview_report().unwrap(); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let cursor = task.pixel; + assert!(plan.milestone(before.next_milestone_index).unwrap() > 2); + for _ in 0..4 { + assert!(!task.partial_preview_ready(preview).unwrap()); + assert_eq!(task.begin_partial_preview(preview).err().unwrap().code, ErrorCode::InvalidRequest); + assert_eq!(task.protected_preview_report().unwrap(), before); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(task.pixel, cursor); + assert!(task.encoder.is_none() && task.pixels.is_empty()); + assert!(task.progressive.as_ref().unwrap().partial.is_none()); + } + assert!(!before.quota_exhausted && !before.milestones_complete); + let milestone = plan.milestone(before.next_milestone_index).unwrap(); + reach_partial_frontier(&mut task, (milestone / 1024) as u32, (milestone % 1024) as usize, &mut Vec::new()); + assert!(task.partial_preview_ready(preview).unwrap(), "later real progress makes a temporary wait eligible"); +} + +#[test] +fn protected_real_coalesced_last_milestone_preserves_unspent_quota_and_final_priority() { + let source = partial_four_pixel_task(5, 123, true); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + reach_partial_frontier(&mut task, 4, 3, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let coalesced = task.protected_preview_report().unwrap(); + assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 7, 7)); + assert!(coalesced.milestones_complete && !coalesced.quota_exhausted); + assert_eq!(coalesced.presentation_used, plan.snapshot_work().unwrap()); + assert!(coalesced.presentation_used < coalesced.presentation_limit); + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + let actual = finish_partial_final(&mut task, true, &mut rays); + let mut control_rays = Vec::new(); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected); + assert_eq!(rays, control_rays); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, control.work.used()); + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); + assert!(task.done, "final never waits to spend unreachable/unused quota"); +} + +#[test] +fn protected_actual_every_pass_and_early_snapshots_exhaust_quota_without_failing_final() { + let source = empty_progressive_source(); + let mut control = shared_partial_rebuild(&source, None); + let expected = finish_partial_final(&mut control, true, &mut Vec::new()); + let ordinary = control.work.used(); + let mut task = protected_rebuild(&source, None); + initial_test_work(&mut task, ordinary, true); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + for index in 0..127 { + let milestone = plan.milestone(index).unwrap(); + reach_partial_frontier(&mut task, (milestone / 1024) as u32, (milestone % 1024) as usize, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.accepted_snapshots, index + 1); + assert_eq!(report.next_milestone_index, index + 1); + assert_eq!(report.presentation_used, u64::from(index + 1) * 79874); + } + let exhausted = task.protected_preview_report().unwrap(); + assert!(exhausted.quota_exhausted && exhausted.milestones_complete); + assert_eq!(exhausted.presentation_used, exhausted.presentation_limit); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let cursor = task.pixel; + for _ in 0..4 { + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Exhausted)); + assert_eq!(task.protected_preview_report().unwrap(), exhausted); + assert_eq!(task.pixel, cursor); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + } + let actual = finish_partial_final(&mut task, true, &mut rays); + assert_eq!(actual, expected); + require_empty_final(&actual.0, &actual.1); + assert_eq!(rays.len(), 65536); + let complete = task.protected_preview_report().unwrap(); + assert_eq!(complete.ordinary_used, ordinary); + assert_eq!(task.work.used(), complete.aggregate_limit, "O reaches its full original T and V exactly Q"); + assert_eq!(complete.presentation_used, 127 * 79874); +} + +#[test] +fn protected_full_pass_snapshot_keeps_the_ordinary_transition_tick_and_report_after_complete() { + let source = partial_four_pixel_task(5, 123, true); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut rays); + reach_partial_frontier(&mut control, 1, 0, &mut control_rays); + let before = task.protected_preview_report().unwrap(); + assert_eq!(before.ordinary_used, control.work.used()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!((task.pixel, control.pixel), (4, 4)); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert!(matches!(control.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + assert_eq!((task.pixel, control.pixel), (0, 0)); + let after = task.protected_preview_report().unwrap(); + assert_eq!(after.ordinary_used, before.ordinary_used + 1); + assert_eq!(after.ordinary_used, control.work.used()); + assert_eq!(after.presentation_used, plan.snapshot_work().unwrap()); + let actual = finish_partial_final(&mut task, true, &mut rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected); + assert_eq!(rays, control_rays); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, control.work.used()); + assert!(control.protected_preview_report().is_none(), "old IF1 has no protected report"); +} + +#[test] +fn protected_cancelled_begin_and_encoder_keep_the_actual_paid_report_without_refund() { + let source = partial_four_pixel_task(5, 123, true); + for debit_first in [false, true] { + let mut task = protected_rebuild(&source, None); + let plan = protected_plan(&task); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + let before = task.protected_preview_report().unwrap(); + if debit_first { + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + for _ in 0..20 { + if task.encoder.is_some() { + break; + } + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + } + assert!(task.encoder.is_some()); + } + let paid = task.protected_preview_report().unwrap(); + task.cancel.cancel(); + let code = if debit_first { + task.step_with_partial_previews(1).err().unwrap().code + } else { + task.begin_partial_preview(plan.preview_plan()).err().unwrap().code + }; + assert_eq!(code, ErrorCode::Cancelled); + assert_eq!(task.protected_preview_report().unwrap(), paid); + assert_eq!(paid.ordinary_used, before.ordinary_used); + assert_eq!(paid.presentation_used, if debit_first { plan.snapshot_work().unwrap() } else { 0 }); + assert_eq!(paid.accepted_snapshots, u32::from(debit_first)); + assert_eq!(paid.next_milestone_index, u32::from(debit_first)); + } +} + +#[test] +fn protected_admission_matches_actual_source_sampling_budget_before_constructing_the_task() { + let source = partial_four_pixel_task(5, 123, true); + let plan = protected_plan(&source); + let protected = + admit_with_protected_partial_preview(source.visibility_owner.source(), &source.request, source.visibility_owner.options(), false, plan) + .unwrap(); + let shared = + admit_with_partial_preview(source.visibility_owner.source(), &source.request, source.visibility_owner.options(), false, plan.preview_plan()) + .unwrap(); + assert_eq!( + protected.estimated_total_bytes, shared.estimated_total_bytes, + "same two slots and source/codec buffers; fixed task layout guard stays required" + ); + for wrong in [ + job::ProtectedPreviewPlan::new(8, 1, 5, source.visibility_owner.options().budget).unwrap(), + job::ProtectedPreviewPlan::new(4, 1, 3, source.visibility_owner.options().budget).unwrap(), + job::ProtectedPreviewPlan::new(4, 1, 5, job::CpuBudget::Studio).unwrap(), + ] { + assert_eq!( + admit_with_protected_partial_preview(source.visibility_owner.source(), &source.request, source.visibility_owner.options(), false, wrong) + .err() + .unwrap() + .code, + ErrorCode::InvalidRequest + ); + assert_eq!( + ImageTask::new_with_environment_and_nested_and_protected_partial( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + None, + false, + wrong + ) + .err() + .unwrap() + .code, + ErrorCode::InvalidRequest + ); + } + assert_eq!(source.visibility_owner.options().emissions.as_ref().unwrap().len(), 1, "original fixture authors one red surface emission"); + let task = protected_rebuild(&source, None); + let report = task.protected_preview_report().unwrap(); + assert_eq!( + (report.ordinary_used, report.presentation_used, report.accepted_snapshots, report.next_milestone_index), + (1, 0, 0, 0), + "one authored emission owes one ordinary construction tick before the first camera sample" + ); + assert_eq!(report.aggregate_limit, plan.aggregate_limit().unwrap()); +} + +#[test] +fn protected_area_and_hdr_reflection_preserve_ordinary_work_absolute_rays_and_final_pixels() { + for area_samples in [1, 4, 16, 64] { + let source = progressive_area_fixture(area_samples, 5, 23, true); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(finish_partial_final(&mut task, true, &mut rays), finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, control.work.used()); + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); + } + let mut source = progressive_fixture(5, 23, Some(true), 0.0); + let (mut fixture_scene, fixture_options) = source.visibility_owner.into_capture(); + fixture_scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 1.0, 0.35, 1.5).unwrap()); + source.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + let mut task = protected_rebuild(&source, Some(partial_original_hdr())); + let mut control = shared_partial_rebuild(&source, Some(partial_original_hdr())); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 1, 0, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(finish_partial_final(&mut task, true, &mut rays), finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, control.work.used()); + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); +} + +#[test] +fn protected_real_sampling_is_independent_of_quantum_and_feedback_schedule() { + for seed in [0, 123] { + let source = partial_four_pixel_task(5, seed, true); + let mut control = shared_partial_rebuild(&source, None); + let expected = finish_partial_final(&mut control, true, &mut Vec::new()); + let ordinary = control.work.used(); + for quantum in [1, 2, 4] { + let mut task = protected_rebuild(&source, None); + let plan = protected_plan(&task); + let mut snapshots = 0_u32; + let mut output = None; + let mut bits = None; + for _ in 0..200_000 { + if bits.is_none() + && let Some(progressive) = &task.progressive + && progressive.film.ready() + && progressive.film.samples() == 5 + { + bits = Some((0..4).map(|i| progressive.film.pixel(i).unwrap().0.map(f64::to_bits)).collect::>()); + } + if snapshots < 3 && task.partial_preview_ready(plan.preview_plan()).unwrap() { + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + snapshots += 1; + } + match task.step_with_partial_previews(quantum).unwrap() { + PartialImagePoll::Pending(_) => {} + PartialImagePoll::Complete(png) => { + output = Some(png); + break; + } + PartialImagePoll::Preview { .. } => panic!("no snapshot was requested in this continuation"), + } + } + assert!(snapshots > 0, "actual safe frontiers must be observed in this original fixture"); + assert_eq!(output.unwrap(), expected.0); + assert_eq!(bits.unwrap(), expected.1); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, ordinary); + assert_eq!(report.accepted_snapshots, snapshots); + assert_eq!(report.presentation_used, u64::from(snapshots) * plan.snapshot_work().unwrap()); + assert_eq!(task.work.used(), ordinary + report.presentation_used); + } + } +} + +#[test] +fn protected_real_one_and_two_camera_commit_jobs_finish_with_exact_zero_or_one_snapshot() { + for samples in [1, 2] { + let source = progressive_fixture(samples, 123, None, 0.0); + let mut task = protected_rebuild(&source, None); + let mut control = shared_partial_rebuild(&source, None); + let plan = protected_plan(&task); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + assert_eq!(plan.quota_limit(), samples - 1); + if samples == 1 { + let initial = task.protected_preview_report().unwrap(); + assert!(initial.quota_exhausted && initial.milestones_complete); + assert_eq!(initial.presentation_limit, 0); + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + } else { + reach_partial_frontier(&mut task, 1, 0, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let _ = finish_partial_snapshot(&mut task); + assert_eq!(task.pixel, 1, "normal complete-pass transition remains pending"); + } + assert_eq!(finish_partial_final(&mut task, true, &mut rays), finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.accepted_snapshots, samples - 1); + assert_eq!(report.presentation_used, u64::from(samples - 1) * plan.snapshot_work().unwrap()); + assert_eq!(report.ordinary_used, control.work.used()); + assert!(report.quota_exhausted && report.milestones_complete); + } +} + +// Original progressive optics / presentation combinations. WRITTEN, NOT RUN. +fn optical_partial_source(samples: u32) -> (ProductScene, ImageRequest, RaytraceOptions) { + let (scene, mut request, options) = super::tests::progressive_optics_source(job::DielectricBoundary::ClosedBox, 2.0, 1.5, samples); + request.width = 2; + (scene, request, options) +} + +#[test] +fn protected_optical_partial_contains_only_whole_drained_camera_trees() { + let (scene, request, options) = optical_partial_source(3); + let plan = job::ProtectedPreviewPlan::new(2, 1, 3, options.budget).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + None, + false, + plan, + ) + .unwrap(); + let mut control = + ImageTask::new_with_environment_and_nested_and_partial(scene, request, CancelToken::default(), options, None, false, plan.preview_plan()) + .unwrap(); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + let mut saw_interior = false; + for _ in 0..100_000 { + let was_empty = task.pending.is_none(); + assert!(matches!(task.step_with_partial_previews(1).unwrap(), PartialImagePoll::Pending(_))); + record_partial_primary(&task, was_empty, &mut rays); + if task.optical.first().and_then(|o| o.pending.as_ref()).is_some_and(|s| s.path.medium.is_some()) { + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap().updated_prefix, 0); + assert!(!task.partial_preview_ready(plan.preview_plan()).unwrap()); + saw_interior = true; + break; + } + } + assert!(saw_interior); + reach_partial_frontier(&mut task, 0, 1, &mut rays); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + assert!(task.optical.first().unwrap().pending.is_none()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let ordinary = task.protected_preview_report().unwrap().ordinary_used; + let (_, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (0, 1)); + assert_eq!(covered, [1, 0], "second pixel is Unknown, never a fabricated optical sample"); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, ordinary); + let actual = finish_partial_final(&mut task, true, &mut rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected, "exact final PNG and linear film bits with observer on/off"); + assert_eq!(rays, control_rays); + assert_eq!(rays.len(), 6); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, control.work.used()); + assert_eq!(report.presentation_used, plan.snapshot_work().unwrap()); +} + +#[test] +fn protected_optical_snapshot_cancellation_cannot_emit_or_commit_another_sample() { + let (scene, request, options) = optical_partial_source(3); + let plan = job::ProtectedPreviewPlan::new(2, 1, 3, options.budget).unwrap(); + let mut task = + ImageTask::new_with_environment_and_nested_and_protected_partial(scene, request, CancelToken::default(), options, None, false, plan).unwrap(); + reach_partial_frontier(&mut task, 0, 1, &mut Vec::new()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let frontier = task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(); + let report = task.protected_preview_report().unwrap(); + task.cancel.cancel(); + assert_eq!(task.step_with_partial_previews(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.progressive.as_ref().unwrap().film.partial_frontier().unwrap(), frontier); + assert_eq!(task.protected_preview_report().unwrap(), report); + assert!(!task.done); +} + +fn with_unit_optical_sheet(source: &ImageTask) -> (ProductScene, ImageRequest, RaytraceOptions) { + let mut scene = source.visibility_owner.source().clone(); + let mut options = source.visibility_owner.options().clone(); + // Original two-triangle rectangle between camera and receiver. It is + // index-matched and lossless: the independent control has no sheet at all. + scene.meshes.push(ProductMesh { + transmission: None, + name: "Progressive optical sheet".into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(-20.0, -20.0, 2.0), Vec3::new(20.0, -20.0, 2.0), Vec3::new(20.0, 20.0, 2.0), Vec3::new(-20.0, 20.0, 2.0)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + ..Default::default() + }), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + options.dielectrics.push(job::DielectricOptions { + body_index: scene.meshes.len() - 1, + body_name: "Progressive optical sheet".into(), + boundary: job::DielectricBoundary::ThinSheet, + ior: 1.0, + absorption_per_mm: [0.0; 3], + thickness_mm: 0.0, + }); + scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds())); + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + (scene, request, options) +} + +#[test] +fn progressive_unit_optics_rejoin_real_area_consumers_at_every_admitted_sample_count() { + for count in [1, 4, 16, 64] { + for seed in [0, 23] { + // Conservative opaque shadow visibility is deliberately off. This + // feature does not invent transmitted illumination or caustics. + let source = progressive_area_fixture(count, 3, seed, false); + let (scene, request, options) = with_unit_optical_sheet(&source); + let optical = ImageTask::new(scene, request, CancelToken::default(), options).unwrap(); + let expected = progressive_complete(source, 1); + let actual = progressive_complete(optical, 4); + assert_eq!(actual.0, expected.0); + assert_eq!(actual.1, expected.1, "unit transmission preserves independently lit receiver; count={count}, seed={seed}"); + assert!(actual.2 > expected.2, "real optical traversal is charged, never bypassed"); + } + } +} + +#[test] +fn progressive_unit_optics_rejoin_hdr_receiver_and_preserve_feedback_film_and_seed() { + let mut source = progressive_area_fixture(4, 3, 23, false); + let (fixture_scene, mut fixture_options) = source.visibility_owner.into_capture(); + fixture_options.area_lights = None; + fixture_options.area_samples = None; + fixture_options.seed = None; + source.request.raytrace = Some(fixture_options.clone()); + source.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, fixture_options); + let (scene, request, options) = with_unit_optical_sheet(&source); + let plan = job::ProtectedPreviewPlan::new(1, 1, 3, options.budget).unwrap(); + let mut observed = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + Some(partial_original_hdr()), + false, + plan, + ) + .unwrap(); + let mut control = ImageTask::new_with_environment_and_nested_and_partial( + scene, + request, + CancelToken::default(), + options, + Some(partial_original_hdr()), + false, + plan.preview_plan(), + ) + .unwrap(); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut observed, 1, 0, &mut rays); + assert!(matches!(observed.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let (snapshot, covered, passes, prefix) = finish_partial_snapshot(&mut observed); + assert_eq!((passes, prefix), (1, 0)); + assert_eq!(covered, [1]); + let actual = finish_partial_final(&mut observed, true, &mut rays); + assert_eq!(actual, finish_partial_final(&mut control, true, &mut control_rays)); + assert_eq!(rays, control_rays); + assert_eq!(observed.protected_preview_report().unwrap().ordinary_used, control.work.used()); + let without_sheet = ImageTask::new_with_environment( + source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), + source.visibility_owner.options().clone(), + Some(partial_original_hdr()), + ) + .unwrap(); + let expected = progressive_complete(without_sheet, 1); + assert_eq!(snapshot, expected.0[0].1); + assert_eq!(actual.0, expected.1); +} + +#[test] +fn protected_deep_identity_shells_preserve_partial_final_rays_film_and_real_work() { + for absorbing in [false, true] { + let (scene, mut request, options) = super::tests::straight_identity_shells_source(8, true, absorbing); + request.width = 2; // orthographic X range[-16,16] remains inside innermost[-17,17]. + let plan = job::ProtectedPreviewPlan::new(2, 1, 3, options.budget).unwrap(); + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene.clone(), + request.clone(), + CancelToken::default(), + options.clone(), + None, + true, + plan, + ) + .unwrap(); + let mut control = + ImageTask::new_with_environment_and_nested_and_partial(scene, request, CancelToken::default(), options, None, true, plan.preview_plan()) + .unwrap(); + let mut rays = Vec::new(); + let mut control_rays = Vec::new(); + reach_partial_frontier(&mut task, 0, 1, &mut rays); + assert!(task.optical.first().unwrap().pending.is_none()); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let ordinary = task.protected_preview_report().unwrap().ordinary_used; + let (_, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!((passes, prefix), (0, 1)); + assert_eq!(covered, [1, 0]); + assert_eq!(task.protected_preview_report().unwrap().ordinary_used, ordinary); + let actual = finish_partial_final(&mut task, true, &mut rays); + let expected = finish_partial_final(&mut control, true, &mut control_rays); + assert_eq!(actual, expected, "exact final PNG and film bits with optional observation"); + assert_eq!(rays, control_rays); + assert_eq!(rays.len(), 6); + let linear = super::tests::straight_shells_expected_linear(8, absorbing); + let expected_pixel = super::tests::straight_expected_pixel(linear); + for rgb in &actual.1 { + for (value, physical) in rgb.iter().copied().map(f64::from_bits).zip(linear) { + assert!((value - physical).abs() < 1e-11); + } + } + let image = ::image::load_from_memory(&actual.0).unwrap().to_rgba8(); + assert_eq!(image.get_pixel(0, 0).0, expected_pixel); + assert_eq!(image.get_pixel(1, 0).0, expected_pixel); + let report = task.protected_preview_report().unwrap(); + assert_eq!(report.ordinary_used, control.work.used()); + assert_eq!(report.presentation_used, plan.snapshot_work().unwrap()); + } +} + +#[test] +fn every_cpu_pass_seven_has_exact_short_job_pngs_across_worker_quanta() { + let run = progressive_complete(progressive_fixture(7, 123, Some(true), 0.0), 1); + assert_eq!(run.0.iter().map(|(samples, _)| *samples).collect::>(), [1, 2, 3, 4, 5, 6]); + assert_eq!(run, progressive_complete(progressive_fixture(7, 123, Some(true), 0.0), 16_384)); + for (samples, png) in &run.0 { + assert_eq!(png, &progressive_complete(progressive_fixture(*samples, 123, Some(true), 0.0), 3).1); + } +} + +#[test] +fn every_cpu_pass_area_sample_keys_preserve_history_and_separate_high_ordinal_blocks() { + for (pixel, ordinal, spatial, primary, expected) in [ + (0_u64, 4095_u32, 0_u8, 1_u8, 0x4152_4541_5341_b2a0_u64), + (0, 4096, 0, 1, 0x8000_0000_1000_0000), + (1, 4096, 0, 1, 0x8000_0010_1000_0000), + (0, 4096, 0, 4, 0x8000_0000_1000_4000), + (0, 4096, 3, 4, 0x8000_0000_1000_4c00), + (0, 1_048_575, 15, 16, 0x8000_000f_ffff_bc00), + (67_108_863, 1_048_575, 15, 16, 0xbfff_ffff_ffff_bc00), + ] { + assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); + } + for pixel in [0_u64, 1, 67_108_863] { + for primary in [1_u8, 4, 16] { + for spatial in 0..primary { + for ordinal in [0_u32, 1, 63, 4095] { + let expected = if primary == 1 && ordinal == 0 { + pixel + } else { + (pixel * 65_536 + u64::from(ordinal) * 16 + u64::from(spatial)) ^ 0x4152_4541_5341_4d50 + }; + assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); + } + for ordinal in [4096_u32, 65_535, 65_536, 1_048_575] { + let mode = match primary { + 1 => 0_u64, + 4 => 1, + 16 => 2, + _ => unreachable!(), + }; + let expected = (1_u64 << 63) | (pixel << 36) | (u64::from(ordinal) << 16) | (mode << 14) | (u64::from(spatial) << 10); + assert_eq!(area_sample_key(pixel, spatial, primary, ordinal).unwrap(), expected); + assert_eq!(expected & 1023, 0); + assert_ne!( + area_sample_key(pixel, spatial, primary, ordinal).unwrap(), + area_sample_key(pixel, spatial, primary, ordinal % 4096).unwrap() + ); + } + } + } + } + assert!(area_sample_key(u64::MAX, 0, 1, 1).is_err()); + assert!(area_sample_key(0, 0, 1, 1_048_576).is_err()); + assert!(area_sample_key(1_u64 << 26, 0, 1, 4096).is_err()); + let mut states = std::collections::BTreeSet::new(); + for pixel in [0_u64, 67_108_863] { + for ordinal in [4096_u32, 65_535, 1_048_575] { + for light in 0..4_u64 { + for sample in 0..64_u64 { + let key = area_sample_key(pixel, 0, 1, ordinal).unwrap(); + let state = key.checked_add(u64::from(u32::MAX) * 65_537 + light * 104_729 + sample * 8191).unwrap(); + assert_ne!(state & (1_u64 << 63), 0); + assert!(states.insert(state), "initial RNG states, not generated UVs, stay distinct"); + } + } + } + } +} + +#[test] +fn every_cpu_pass_display_uses_full_u32_coverage_without_saturation() { + assert_eq!(composite_spatial(Vec3::ZERO, 65_536, 65_536, [13, 27, 41], 0.0).unwrap(), [0, 0, 0, 255]); + assert_eq!(composite_spatial(Vec3::ZERO, 0, 65_536, [13, 27, 41], 0.0).unwrap(), [13, 27, 41, 255]); + assert!(composite_spatial(Vec3::ZERO, 65_537, 65_536, [13, 27, 41], 0.0).is_err()); +} + +#[test] +#[cfg(target_pointer_width = "64")] +fn every_cpu_pass_actual_65536_film_resolves_one_u32_snapshot_and_unique_final() { + let source = fixture(1, 1, None); + let mut options = source.visibility_owner.options().clone(); + options.budget = job::CpuBudget::Workstation; + options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 65_537, seed: 123 }); + let plan = job::ProtectedPreviewPlan::new(1, 1, 65_537, job::CpuBudget::Workstation).unwrap(); + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + source.visibility_owner.source().clone(), + request, + CancelToken::default(), + options, + None, + false, + plan, + ) + .unwrap(); + let mut reached = false; + for _ in 0..2_000_000 { + if task.progressive.as_ref().is_some_and(|state| state.film.ready() && state.film.samples() == 65_536) + && task.partial_preview_ready(plan.preview_plan()).unwrap() + { + reached = true; + break; + } + assert!(matches!(task.step_with_partial_previews(16_384).unwrap(), PartialImagePoll::Pending(_))); + } + assert!(reached); + let (linear, covered, count) = task.progressive.as_ref().unwrap().film.pixel(0).unwrap(); + assert_eq!(linear, [0.0; 3]); + assert_eq!((covered, count), (0, 65_536)); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let (png, covered, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!(covered, [0]); + assert_eq!((passes, prefix), (65_536, 0)); + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); + let report = task.protected_preview_report().unwrap(); + assert_eq!((report.accepted_snapshots, report.next_milestone_index), (1, 65_536)); + assert_eq!(report.presentation_used, 65_552); + let (final_png, bits) = finish_partial_final(&mut task, true, &mut Vec::new()); + assert_eq!(::image::load_from_memory(&final_png).unwrap().to_rgba8().get_pixel(0, 0).0, [255; 4]); + assert_eq!(bits, [[0.0_f64.to_bits(); 3]]); + assert!(task.done && task.progressive.is_none()); +} + +#[test] +fn sparse_checkpoint_compatibility_preserves_each_final_png_and_deterministic_sample_prefix() { + for (target, expected_sparse) in [(1, vec![]), (3, vec![1, 2]), (5, vec![1, 2, 4]), (9, vec![1, 2, 4, 8])] { + let current = progressive_fixture(target, 19, Some(true), 1.0); + let source = current.visibility_owner.source().clone(); + let options = current.visibility_owner.options().clone(); + let mut legacy_request = current.request.clone(); + legacy_request.cpu_progressive_every_pass = false; + let legacy = ImageTask::new(source, legacy_request, CancelToken::default(), options).unwrap(); + let (each_previews, each_final, _) = progressive_complete(current, 1); + let (legacy_previews, legacy_final, _) = progressive_complete(legacy, 3); + assert_eq!(each_previews.iter().map(|(samples, _)| *samples).collect::>(), (1..target).collect::>()); + assert_eq!(legacy_previews.iter().map(|(samples, _)| *samples).collect::>(), expected_sparse); + assert_eq!(legacy_final, each_final, "publication policy must not change the requested final PNG"); + for (samples, png) in legacy_previews { + assert_eq!(png, each_previews.iter().find(|(count, _)| *count == samples).unwrap().1); + } + } +} + +#[test] +fn legacy_protected_producer_consumes_the_original_global_milestones_without_changing_final_pixels() { + let (scene, mut request, options) = partial_four_pixel_source(5, 29); + request.cpu_progressive_every_pass = false; + let reference = ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); + let (_, expected_png, _) = progressive_complete(reference, 3); + let plan = job::ProtectedPreviewPlan::with_cadence(request.width, request.height, 5, options.budget, false).unwrap(); + assert_eq!((plan.total_commits(), plan.quota_limit()), (20, 19)); + let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, request, CancelToken::default(), options, None, false, plan, + ) + .unwrap(); + let mut rays = Vec::new(); + for committed in 1..20 { + reach_partial_frontier(&mut task, (committed / 4) as u32, (committed % 4) as usize, &mut rays); + assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); + let (_, _, passes, prefix) = finish_partial_snapshot(&mut task); + assert_eq!(u64::from(passes) * 4 + prefix, committed); + let report = task.protected_preview_report().unwrap(); + assert_eq!((report.accepted_snapshots, report.next_milestone_index), (committed as u32, committed as u32)); + assert_eq!(report.quota_limit, 19); + } + let (actual_png, _) = finish_partial_final(&mut task, true, &mut rays); + assert_eq!(actual_png, expected_png); + let report = task.protected_preview_report().unwrap(); + assert_eq!((report.accepted_snapshots, report.quota_limit), (19, 19)); + assert_eq!(report.presentation_used, 19 * plan.snapshot_work().unwrap()); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/punctual_image_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/punctual_image_tests.rs new file mode 100644 index 000000000..f234033cb --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/punctual_image_tests.rs @@ -0,0 +1,281 @@ +use super::*; +use crate::{ProductMesh, StandardView, job::PunctualLightOptions}; +use solidcraft_geom::{Aabb3, Mesh}; +use std::sync::Arc; + +fn plane(name: &str, x: f64, z: f64, half: f64) -> ProductMesh { + ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(Mesh { + positions: vec![Vec3::new(x - half, -half, z), Vec3::new(x + half, -half, z), Vec3::new(x + half, half, z), Vec3::new(x - half, half, z)], + normals: vec![Vec3::Z; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + 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 task(blocker: Option<(f64, f64)>, shadows: bool) -> ImageTask { + let mut meshes = vec![plane("receiver", 0.0, 0.0, 30.0)]; + if let Some((x, z)) = blocker { + meshes.push(plane("blocker", x, z, 2.0)); + } + let bounds = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + let scene = ProductScene { meshes, bounds }; + let mut camera = crate::Camera { distance: 80.0, fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Top); + let options = RaytraceOptions { + lights: Some(Vec::new()), + punctual_lights: Some(vec![PunctualLightOptions { + position_mm: [20.0, 0.0, 10.0], + color: [1.0, 0.5, 0.25], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }]), + shadows, + ..Default::default() + }; + let request = ImageRequest { + cpu_progressive_every_pass: true, + 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(options.clone()), + camera, + width: 1, + height: 1, + background: [13, 27, 41], + transparent_background: false, + }; + ImageTask::new(scene, request, CancelToken::default(), options).unwrap() +} + +fn render(mut task: ImageTask) -> [u8; 4] { + for _ in 0..100_000 { + let before = task.work.used(); + let poll = task.step(1).unwrap(); + assert!(task.work.used() - before <= 1); + if let TaskPoll::Complete(png) = poll { + return ::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0; + } + } + panic!("bounded punctual PNG never completed"); +} + +#[test] +fn actual_consumer_matches_analytic_rgb_and_finite_source_occlusion() { + let lit = render(task(None, true)); + // White rough conductor, normal view: f*cos=cos/[2*pi*(1+cos)]. + let cosine = 1.0 / 5.0_f64.sqrt(); + let l = 0.2 * cosine / (2.0 * std::f64::consts::PI * (1.0 + cosine)); + for (actual, factor) in lit.into_iter().take(3).zip([1.0, 0.5, 0.25]) { + let expected = encode8(l * factor / (1.0 + l * factor)); + assert!(actual.abs_diff(expected) <= 1, "actual={actual}, expected={expected}"); + } + assert_eq!(render(task(Some((10.0, 5.0)), true)), [0, 0, 0, 255]); + assert_eq!(render(task(Some((40.0, 20.0)), true)), lit, "geometry behind source cast a shadow"); + assert_eq!(render(task(Some((10.0, 5.0)), false)), lit); +} + +#[test] +fn actual_spot_consumer_uses_emitted_world_axis_and_cone() { + let point = render(task(None, true)); + for (axis, expected) in [([-20.0, 0.0, -10.0], point), ([20.0, 0.0, 10.0], [0, 0, 0, 255])] { + let previous = task(None, true); + let mut options = previous.visibility_owner.options().clone(); + options.punctual_lights.as_mut().unwrap()[0].cone = + Some(job::SpotConeOptions { emitted_axis: axis, inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); + let mut request = previous.request.clone(); + request.raytrace = Some(options.clone()); + let actual = ImageTask::new(previous.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + assert_eq!(render(actual), expected); + } +} + +#[test] +fn cancellation_between_final_shadow_and_sum_prevents_publication() { + let mut task = task(None, true); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.punctual_ready) { + assert!(task.pixels.is_empty()); + let before = task.work.used(); + task.cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + assert_eq!(task.work.used(), before); + assert!(task.pixels.is_empty()); + return; + } + } + panic!("final punctual shadow continuation was not reached"); +} + +#[test] +fn punctual_work_exhaustion_is_shared_and_task_metadata_remains_bounded() { + assert!(std::mem::size_of::() <= 4096); + let mut task = task(None, true); + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.punctual_shadow) { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + assert!(task.pixels.is_empty()); + return; + } + } + panic!("punctual shadow traversal was not reached"); +} + +fn mixed(n: u32, shadows: bool) -> ImageTask { + let previous = task(None, shadows); + let mut options = previous.visibility_owner.options().clone(); + options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]); + options.punctual_lights = Some(vec![options.punctual_lights.as_ref().unwrap()[0]; 8]); + options.area_lights = Some(vec![ + job::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [8.0, 0.0, 0.0], + edge_v_mm: [0.0, -0.5, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0 + }; + 4 + ]); + options.area_samples = Some(n); + let mut request = previous.request.clone(); + request.raytrace = Some(options.clone()); + ImageTask::new(previous.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() +} + +#[test] +fn max_union_observes_272_direct_attempts_in_one_budget_and_partition_independent_png() { + for n in [1, 4, 16, 64] { + let mut task = mixed(n, false); + let mut point_attempts = 0; + let mut area_attempts = 0; + let mut actual = None; + for _ in 0..100_000 { + if let Some(p) = task.pending.as_ref().filter(|p| p.hit.is_some() && p.light == 8) { + if p.punctual_index < 8 && !p.punctual_ready && !p.punctual_shadow { + point_attempts += 1; + } + if p.punctual_index == 8 && p.area_light < 4 && p.area_index < n && !p.area_ready && !p.area_shadow { + area_attempts += 1; + } + } + let before = task.work.used(); + let poll = task.step(1).unwrap(); + assert!(task.work.used() - before <= 1); + if let TaskPoll::Complete(png) = poll { + actual = Some(png); + break; + } + } + let actual = actual.unwrap(); + assert_eq!(point_attempts, 8); + assert_eq!(area_attempts, 4 * n); + assert_eq!(8 + point_attempts + area_attempts, 16 + 4 * n); + if n == 64 { + assert_eq!(8 + point_attempts + area_attempts, 272); + } + let mut other = mixed(n, false); + let mut complete = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = other.step(128).unwrap() { + complete = Some(png); + break; + } + } + assert_eq!(actual, complete.unwrap()); + } +} + +#[test] +fn mixed_area_final_shadow_cancellation_and_shared_exhaustion_prevent_publication() { + for cancel in [false, true] { + let mut task = mixed(64, true); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.area_light == 3 && p.area_index == 63 && p.area_ready) { + reached = true; + assert!(task.pixels.is_empty()); + let before = task.work.used(); + if cancel { + task.cancel.cancel(); + } else { + task.work.limit = before; + } + assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); + assert_eq!(task.work.used(), before); + assert!(task.pixels.is_empty()); + break; + } + } + assert!(reached, "last rectangle sample continuation was not reached"); + } +} + +#[test] +fn mixed_normal_incidence_radiance_is_summed_before_single_display_transform() { + let mut task = mixed(1, false); + let (fixture_scene, mut options) = task.visibility_owner.into_capture(); + for point in options.punctual_lights.as_mut().unwrap() { + point.position_mm = [0.0, 0.0, 10.0]; + point.color = [1.0; 3]; + point.reference_distance_mm = 10.0; + } + for area in options.area_lights.as_mut().unwrap() { + area.color = [1.0; 3]; + } + task.request.raytrace = Some(options.clone()); + task.visibility_owner = dielectric::DirectVisibilityOwner::new(fixture_scene, options); + // White rough conductor at normal incidence: f*cos=1/(4*pi). + // Eight unit directionals + eight unit point sources + four Le*A/r²=.08 rectangles. + let linear = (8.0 + 8.0 + 4.0 * 0.08) / (4.0 * std::f64::consts::PI); + let expected = encode8(linear / (1.0 + linear)); + assert_eq!(render(task), [expected, expected, expected, 255]); +} + +#[test] +fn scene_dependent_punctual_singularities_complete_and_keep_diagnostic_counts() { + for (height, reference, near_source) in [(0.0, 10.0, true), (0.0009, 10.0, true), (0.001, 1e6, false)] { + let previous = task(None, true); + let mut options = previous.visibility_owner.options().clone(); + let light = &mut options.punctual_lights.as_mut().unwrap()[0]; + light.position_mm = [0.0, 0.0, height]; + light.reference_distance_mm = reference; + light.intensity = 64.0; + let mut request = previous.request.clone(); + request.raytrace = Some(options.clone()); + let mut work = ImageTask::new(previous.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + let mut completed = false; + for _ in 0..100_000 { + if let TaskPoll::Complete(png) = work.step(1).unwrap() { + assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [0, 0, 0, 255]); + let report = work.punctual_diagnostics().unwrap(); + if near_source { + assert!(report.near_source > 0); + } else { + assert!(report.radiance_limit > 0); + } + completed = true; + break; + } + } + assert!(completed, "singular sample must not fail or stall the image"); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/reflection_image_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/reflection_image_tests.rs new file mode 100644 index 000000000..76c8cc8bc --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/candidate/crates/render/src/raytrace/reflection_image_tests.rs @@ -0,0 +1,329 @@ +use super::*; +use crate::ProductMesh; +use crate::job::{ReflectionBody, ReflectionMode, ReflectionOptions}; +use solidcraft_geom::Mesh; +use std::sync::Arc; + +fn visible_second_body_fixture(spatial: u8, samples: u8) -> ImageTask { + let mut source = scene(); + source.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()); + source.meshes[0].mesh = Arc::new(Mesh { + positions: vec![ + Vec3::new(-100.0, -100.0, -100.0), + Vec3::new(100.0, -100.0, -100.0), + Vec3::new(100.0, 100.0, 100.0), + Vec3::new(-100.0, 100.0, 100.0), + ], + normals: vec![Vec3::new(0.0, -1.0, 1.0); 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }); + // Camera and reflector lie INSIDE this separate inward-facing box. A + // primary hits the nearer reflector first; every valid secondary leaving + // it eventually intersects body1. No emitter or test-only transport hook. + let mut target = Mesh::default(); + for normal in [Vec3::X, -Vec3::X, Vec3::Y, -Vec3::Y, Vec3::Z, -Vec3::Z] { + let tangent = if normal.x == 0.0 { Vec3::X } else { Vec3::Y }; + let bitangent = normal.cross(tangent); + let center = -normal * 10_000.0; + let first = target.positions.len() as u32; + for (x, y) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] { + target.positions.push(center + tangent * (x * 10_000.0) + bitangent * (y * 10_000.0)); + target.normals.push(normal); + } + target.triangles.extend([[first, first + 1, first + 2], [first, first + 2, first + 3]]); + target.tri_face.extend([0, 0]); + } + source.meshes[1].mesh = Arc::new(target); + source.bounds = source.meshes.iter().fold(solidcraft_geom::Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds())); + let mut req = request(Some(reflection_options(ReflectionMode::RoughSpecular))); + req.width = 1; + req.height = 1; + // Perspective near clipping starts inside the box. Orthographic near + // clipping includes geometry behind the eye and starts outside this box. + // tan(0.25) < 1/3: the whole film hits |x|, |y|=|z| < 25, within + // the reflector extent100 and before any target box wall10000. + req.camera.fov = 0.5; + let options = req.raytrace.as_mut().unwrap(); + options.primary_samples = spatial; + options.reflections.as_mut().unwrap().samples = samples; + options.reflections.as_mut().unwrap().max_bounces = 1; + let options = options.clone(); + ImageTask::new(source, req, CancelToken::default(), options).unwrap() +} + +#[test] +fn visible_transport_hits_a_real_second_body_and_completes_all_spatial_reflection_attempts() { + for spatial in [1_u8, 4, 16] { + for samples in [1_u8, 4, 16, 64] { + let mut task = visible_second_body_fixture(spatial, samples); + let mut primary_attempts = std::collections::BTreeSet::new(); + let mut secondary_spawns = std::collections::BTreeSet::new(); + let mut second_body_hits = std::collections::BTreeSet::new(); + let expected = usize::from(spatial) * usize::from(samples); + let mut completed = None; + for _ in 0..200_000 { + let absent = task.pending.is_none(); + let work = task.work.used(); + let poll = task.step(1).unwrap(); + assert!(task.work.used() - work <= 4); + if let Some(pending) = task.pending.as_ref() { + let key = (task.spatial, task.sample); + if absent && pending.bounce == 0 { + assert!(primary_attempts.insert(key), "a fixed S,R attempt was retried"); + } + if pending.bounce == 0 + && let Some(hit) = pending.hit + { + assert_eq!(task.looks[hit.primitive_index].body_index, 0, "every primary must reach the selected reflector first"); + } + if pending.bounce == 1 { + secondary_spawns.insert(key); + if let Some(hit) = pending.hit { + assert_eq!(task.looks[hit.primitive_index].body_index, 1, "spawn alone is insufficient: resolve body identity"); + second_body_hits.insert(key); + } + } + } + if !task.pixels.is_empty() { + assert_eq!(primary_attempts.len(), expected, "pixel published before every S*R attempt, including nulls"); + } + if let TaskPoll::Complete(png) = poll { + completed = Some(png); + break; + } + } + assert_eq!(task.pixel, 1); + assert!(task.done); + assert_eq!(primary_attempts.len(), expected); + assert_eq!(second_body_hits, secondary_spawns, "every accepted secondary must finish tracing its actual second body"); + if spatial == 1 { + assert!(!second_body_hits.is_empty(), "the centre fixture must actually hit another body"); + if samples == 64 { + assert!(secondary_spawns.len() < expected, "unit roughness must also exercise null attempts without retry/renormalization"); + } + } + let decoded = ::image::load_from_memory(&completed.expect("bounded full S*R traversal did not complete")).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (1, 1)); + assert_eq!(decoded.get_pixel(0, 0).0[3], 255); + } + } +} + +#[test] +fn visible_rough_transport_keeps_cancellation_and_work_caps_at_sample_count_extremes() { + for samples in [1, 4, 16, 64] { + for cancel_now in [false, true] { + let mut reflection = reflection_options(ReflectionMode::RoughSpecular); + reflection.samples = samples; + let request = request(Some(reflection)); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + let before = task.work.used(); + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + assert!(task.work.used() - before <= 4, "public quantum expanded"); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + reached = true; + break; + } + } + assert!(reached, "actual VNDF rough continuation was not exercised"); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } + } +} + +fn scene() -> ProductScene { + fn quad(name: &str, positions: Vec, normal: Vec3, color: [u8; 3], surface: Option) -> ProductMesh { + ProductMesh { + transmission: None, + name: name.into(), + mesh: Arc::new(Mesh { + positions, + normals: vec![normal; 4], + triangles: vec![[0, 1, 2], [0, 2, 3]], + tri_face: vec![0, 0], + ..Default::default() + }), + color, + opacity: 1.0, + surface, + faces: Vec::new(), + } + } + let mirror = quad( + "Mirror", + vec![Vec3::new(-20.0, -20.0, -20.0), Vec3::new(20.0, -20.0, -20.0), Vec3::new(20.0, 20.0, 20.0), Vec3::new(-20.0, 20.0, 20.0)], + Vec3::new(0.0, -1.0, 1.0), + [255; 3], + Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 0.2, 1.5).unwrap()), + ); + let object = quad( + "Orange target", + vec![Vec3::new(-8.0, -8.0, 10.0), Vec3::new(-8.0, 8.0, 10.0), Vec3::new(8.0, 8.0, 10.0), Vec3::new(8.0, -8.0, 10.0)], + -Vec3::Z, + [240, 80, 20], + None, + ); + let meshes = vec![mirror, object]; + let bounds = meshes.iter().fold(solidcraft_geom::Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds())); + ProductScene { meshes, bounds } +} +fn request(reflections: Option) -> ImageRequest { + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Front); + ImageRequest { + cpu_progressive_every_pass: true, + 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 { + reflections, + shadows: false, + lights: Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, -1.0], color: [1.0; 3], intensity: 2.0 }]), + ..Default::default() + }), + camera, + width: 9, + height: 9, + background: [13, 27, 41], + transparent_background: false, + } +} +fn reflection_options(mode: ReflectionMode) -> ReflectionOptions { + ReflectionOptions { bodies: vec![ReflectionBody { body: "Mirror".into(), mode }], max_bounces: 2, samples: 16 } +} +fn render(request: ImageRequest) -> Vec { + let options = request.raytrace.clone().unwrap(); + let mut task = ImageTask::new(scene(), request, CancelToken::default(), options).unwrap(); + for _ in 0..200_000 { + if let TaskPoll::Complete(png) = task.step(16384).unwrap() { + return png; + } + } + panic!("bounded reflection fixture did not complete"); +} +#[test] +fn mirror_png_contains_other_body_and_rough_transport_is_reproducible() { + let baseline = ::image::load_from_memory(&render(request(None))).unwrap().to_rgba8(); + let mirrored = ::image::load_from_memory(&render(request(Some(reflection_options(ReflectionMode::Mirror))))).unwrap().to_rgba8(); + let b = baseline.get_pixel(4, 4).0; + let p = mirrored.get_pixel(4, 4).0; + assert!(p[0] > p[1] && p[1] > p[2], "actual orange object must be reflected: {p:?}"); + assert_ne!(p, b, "reflection must change the scene image, not only metadata"); + let rough = request(Some(reflection_options(ReflectionMode::RoughSpecular))); + assert_eq!(render(rough.clone()), render(rough)); +} +#[test] +fn explicit_empty_overrides_preserve_baseline_bytes_and_validate_names_atomically() { + assert_eq!(render(request(None)), render(request(Some(ReflectionOptions::default())))); + let mut options = reflection_options(ReflectionMode::Mirror); + options.bodies[0].body = "missing".into(); + let request = request(Some(options)); + assert_eq!(admit(&scene(), &request, request.raytrace.as_ref().unwrap()).err().unwrap().code, ErrorCode::InvalidRequest); + let hostile = ReflectionOptions { bodies: Vec::with_capacity(65), ..ReflectionOptions::default() }; + assert!(hostile.validate().is_err()); +} +#[test] +fn reflection_cancel_and_work_exhaustion_never_publish_partial_frame() { + for mode in [ReflectionMode::Mirror, ReflectionMode::RoughSpecular] { + for cancel_now in [false, true] { + let request = request(Some(reflection_options(mode))); + let options = request.raytrace.clone().unwrap(); + let cancel = CancelToken::default(); + let mut task = ImageTask::new(scene(), request, cancel.clone(), options).unwrap(); + let mut reached = false; + for _ in 0..100_000 { + assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); + if task.pending.as_ref().is_some_and(|p| p.bounce > 0) { + reached = true; + break; + } + } + assert!(reached); + if cancel_now { + cancel.cancel(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); + } else { + task.work.limit = task.work.used(); + assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded); + } + } + } +} +#[test] +fn prepared_hit_preserves_original_winding_identity_and_never_certifies_glass() { + let source = scene(); + let primitive = &source.meshes[0]; + let indices = primitive.mesh.triangles[0]; + let vertices = indices.map(|i| primitive.mesh.positions[i as usize]); + let triangle = Triangle::new(vertices).unwrap(); + let ray = Ray::new(Vec3::new(2.0, -50.0, 0.0), Vec3::Y, 0.0, 100.0).unwrap(); + let geometry = triangle.intersect(&ray).unwrap(); + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(vec![triangle], limits(job::CpuBudget::Compact), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let primitives = + [PreparedPrimitive { body_index: 0, face: Some(0), vertices, normals: [geometry.geometric_normal; 3], surface: primitive.surface.unwrap() }]; + let prepared = PreparedScene { bvh: &bvh, primitives: &primitives, source: &source }; + let shared = prepared.resolve_hit(ray, super::super::Hit { primitive_index: 0, geometry }).unwrap(); + assert_eq!(shared.body_name, "Mirror"); + assert_eq!(shared.geometric_normal, geometry.geometric_normal); + assert_eq!(shared.front_face, geometry.front_face); + assert_eq!(prepared.boundary_status(0), super::super::prepared::BoundaryStatus::Unknown); +} +#[test] +fn shared_spawn_excludes_signed_zero_self_hit_without_skipping_thin_blockers() { + for x in [0.0, 1e12 - 100.0] { + let vertices = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 20.0, 0.0, 0.0), Vec3::new(x, 20.0, 0.0)]; + let triangle = Triangle::new(vertices).unwrap(); + let ray = Ray::new(Vec3::new(x + 5.0, 5.0, 10.0), -Vec3::Z, 0.0, 20.0).unwrap(); + let geometry = triangle.intersect(&ray).unwrap(); + let primitive = PreparedPrimitive { + body_index: 0, + face: Some(0), + vertices, + normals: [Vec3::Z; 3], + surface: OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 0.7, 1.5).unwrap(), + }; + let source = ProductScene { + meshes: vec![ProductMesh { + transmission: None, + name: "Plane".into(), + mesh: Arc::new(Mesh::default()), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds: Default::default(), + }; + let cancel = CancelToken::default(); + let mut builder = BvhBuilder::new(vec![triangle], limits(job::CpuBudget::Compact), &cancel).unwrap(); + while !builder.step(1, &cancel).unwrap().complete {} + let bvh = builder.finish().unwrap(); + let primitives = [primitive]; + let prepared = PreparedScene { bvh: &bvh, primitives: &primitives, source: &source }; + let hit = prepared.resolve_hit(ray, super::super::Hit { primitive_index: 0, geometry }).unwrap(); + let secondary = hit.spawn(Vec3::Z).unwrap(); + assert!(secondary.interval()[0] > 0.0); + assert!(triangle.intersect(&secondary).is_none()); + assert!(Triangle::new(vertices.map(|v| v + Vec3::Z * 0.005)).unwrap().intersect(&secondary).is_some()); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/delta-LF-review.patch b/proposals/render/2026-10-31/progressive-compatibility-wip/core/delta-LF-review.patch new file mode 100644 index 000000000..6ddcb62b3 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/delta-LF-review.patch @@ -0,0 +1,846 @@ +--- a/crates/engine/src/cmd/render.rs ++++ b/crates/engine/src/cmd/render.rs +@@ -124,7 +124,7 @@ + CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", resources::capture_settings).icon("settings").doc_only() + .params("name, set: typed CPU/GPU setup patch with hdr/environment unset; path: scoped HDR; expected_sha256?: digest returned by render.hdr.inspect (changed sources refuse); rotation_rad?:0, intensity?:1; samples?:1/4/16/64 for CPU only (default16); assume_linear_srgb?:false for GPU only. Captures immutable bytes and saves resource plus setup atomically in one undo, without a host; returns name/setup/resource metadata, never source bytes"), + CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only() +- .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace, transient studio_weights, raster_lights and progressive_feedback may accompany it. raster_lights?: transient null (legacy studio) or 0..8 directional sources {direction:[x,y,z],color:[linear r,g,b],intensity:0..64}; empty array is dark direct lighting. Requires builtin Raster without studio_weights, raytrace, HDR, transmission or other method controls; existing RenderSetup.exposure_ev is captured for Raster within -32..32. Directions are finite/nonzero and bounded by 1e9; RGB is 0..1. Not saved; no shadows or physical glass. raster_punctual_lights?: transient null or 0..8 shared point/spot sources {position_mm:[x,y,z],color:[linear r,g,b],intensity:0..64,reference_distance_mm:0.001..1000000,minimum_distance_mm:0.001..reference_distance_mm,cone?:{emitted_axis:[x,y,z],inner_half_angle_radians,outer_half_angle_radians}}. Spot angles require 0<=inner>, + progressive_feedback: bool, ++ #[serde(default, deserialize_with = "cpu_progressive_every_pass_input")] ++ cpu_progressive_every_pass: Option, + nested_media: bool, + studio_weights: Option<[f64; 3]>, + progressive: bool, +@@ -34,6 +36,11 @@ + settings: Option, + transparent_background: bool, + replace: bool, ++} ++ ++// Omission is allowed; an explicitly supplied null/string/number is not a bool. ++fn cpu_progressive_every_pass_input<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result, D::Error> { ++ bool::deserialize(deserializer).map(Some) + } + + #[derive(Deserialize)] +@@ -155,6 +162,7 @@ + } + } + let final_request = ImageRequest { ++ cpu_progressive_every_pass: input.cpu_progressive_every_pass.unwrap_or(true), + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -203,6 +211,69 @@ + + #[cfg(test)] + mod union_lowering_tests { ++ #[test] ++ fn cpu_cadence_wire_rejects_null_nonbool_and_nonprogressive_controls_before_capture() { ++ let mut wire = json!({"cpu_progressive_every_pass":false}); ++ assert_eq!(Start::deserialize(&wire).unwrap().cpu_progressive_every_pass, Some(false)); ++ assert_eq!(Start::deserialize(&json!({})).unwrap().cpu_progressive_every_pass, None); ++ for invalid in [Value::Null, json!(0), json!("false"), json!([]), json!({})] { ++ wire["cpu_progressive_every_pass"] = invalid; ++ assert!(Start::deserialize(&wire).is_err()); ++ } ++ for params in [ ++ json!({"cpu_progressive_every_pass":false}), ++ json!({"cpu_progressive_every_pass":true,"integrator":"raytrace","raytrace":{}}), ++ json!({"cpu_progressive_every_pass":false,"progressive":true}), ++ ] { ++ let error = prepare(&Session::default(), ¶ms, "render.preflight").err().unwrap().to_string(); ++ assert!(error.contains("cpu_progressive_every_pass requires CPU progressive raytracing"), "{error}"); ++ } ++ } ++ ++ #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] ++ #[test] ++ fn saved_cpu_cadence_command_replay_normalizes_false_and_keeps_it_through_the_native_worker() { ++ let mut session = Session::default(); ++ let host = solidcraft_render::job::CpuHost::for_platform().unwrap(); ++ session.set_render_job_host(Some(host)).unwrap(); ++ let document = session.doc.to_json(); ++ let original = json!({"settings":{"width":4,"height":3,"background":[17,31,59], ++ "job":{"method":"cpu_raytrace","options":{"lights":[],"shadows":false,"progressive":{"samples_per_pixel":5,"seed":97}}}}, ++ "cpu_progressive_every_pass":false}); ++ let replay: Value = serde_json::from_str(&serde_json::to_string(&original).unwrap()).unwrap(); ++ assert_eq!(replay, original); ++ let normalized = normalize_saved_job(&session, &replay, "render.start").unwrap().unwrap(); ++ assert_eq!(normalized.params["cpu_progressive_every_pass"], false); ++ assert!(normalized.params["settings"]["job"].is_null()); ++ let prepared = prepare(&session, &replay, "render.preflight").unwrap(); ++ assert!(!prepared.request.cpu_progressive_every_pass); ++ assert_eq!(prepared.reply["request"]["cpu_progressive_every_pass"], false); ++ let decoded: ImageRequest = serde_json::from_value(prepared.reply["request"].clone()).unwrap(); ++ assert!(!decoded.cpu_progressive_every_pass); ++ assert_eq!(decoded.raytrace.as_ref().unwrap().progressive.unwrap().seed, 97); ++ let mut reference: Option> = None; ++ for every_pass in [false, true] { ++ let mut params = replay.clone(); ++ params["cpu_progressive_every_pass"] = json!(every_pass); ++ let started = start(&mut session, ¶ms).unwrap(); ++ let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); ++ let handle = session.render_job_handle(id).unwrap(); ++ let status = handle.wait_timeout(std::time::Duration::from_secs(20)).unwrap(); ++ assert_eq!(status.progress.phase, solidcraft_render::job::Phase::Completed); ++ assert_eq!(status.request.cpu_progressive_every_pass, every_pass); ++ let status_wire = serde_json::to_value(&status).unwrap(); ++ assert_eq!(status_wire["request"].get("cpu_progressive_every_pass"), (!every_pass).then_some(&Value::Bool(false))); ++ let frame = handle.frame().unwrap().unwrap(); ++ if let Some(expected) = &reference { ++ assert_eq!(frame.png(), expected.as_slice()); ++ } else { ++ reference = Some(frame.png().to_vec()); ++ } ++ } ++ assert_eq!(session.doc.to_json(), document, "runtime cadence cannot become saved document intent"); ++ } ++ ++ + + #[cfg(not(target_arch = "wasm32"))] + fn raster_local_command_fixture() -> (Session, Value) { +@@ -755,6 +826,7 @@ + | "replace" + | "studio_weights" + | "progressive_feedback" ++ | "cpu_progressive_every_pass" + | "raster_lights" + | "raster_punctual_lights" + | "raster_area_lights" +@@ -820,6 +892,9 @@ + if let Some(feedback) = object.get("progressive_feedback") { + lowered["progressive_feedback"] = feedback.clone(); + } ++ if let Some(every_pass) = object.get("cpu_progressive_every_pass") { ++ lowered["cpu_progressive_every_pass"] = every_pass.clone(); ++ } + Ok(Some(Normalized { params: lowered, hdr, surfaces, optics })) + } + +@@ -828,6 +903,9 @@ + let saved_hdr = normalized.as_ref().and_then(|normalized| normalized.hdr.as_ref()); + let params = normalized.as_ref().map_or(params, |normalized| &normalized.params); + if params.get("progressive").and_then(Value::as_bool) == Some(true) { ++ if params.get("cpu_progressive_every_pass").is_some() { ++ return Err(bad(command, "cpu_progressive_every_pass requires CPU progressive raytracing")); ++ } + let hdr = match saved_hdr { + Some(SavedHdr::Gpu(hdr)) => Some(*hdr), + Some(SavedHdr::Cpu(_)) => return Err(bad(command, "saved CPU HDR cannot enter a GPU request")), +@@ -856,6 +934,11 @@ + )); + } + let mut input = Start::deserialize(params).map_err(|e| bad(command, e.to_string()))?; ++ if input.cpu_progressive_every_pass.is_some() ++ && (input.integrator != Integrator::Raytrace || input.progressive || input.raytrace.as_ref().and_then(|options| options.progressive).is_none()) ++ { ++ return Err(bad(command, "cpu_progressive_every_pass requires CPU progressive raytracing")); ++ } + solidcraft_render::job::validate_raster_lights(&input.raster_lights).map_err(job_error)?; + solidcraft_render::job::validate_raster_punctual_lights(&input.raster_punctual_lights).map_err(job_error)?; + solidcraft_render::job::validate_raster_area_lights(&input.raster_area_lights).map_err(job_error)?; +@@ -1052,6 +1135,7 @@ + return Err(bad(command, "resolved executor is not installed as an image job host")); + } + let request = ImageRequest { ++ cpu_progressive_every_pass: input.cpu_progressive_every_pass.unwrap_or(true), + raster_punctual_lights: input.raster_punctual_lights.take(), + raster_area_lights: input.raster_area_lights.take(), + raster_exposure_ev: if input.integrator == Integrator::Raster { settings.exposure_ev } else { 0.0 }, +@@ -1285,6 +1369,7 @@ + return Err(bad(command, "image host is unavailable")); + } + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/engine/src/render_jobs.rs ++++ b/crates/engine/src/render_jobs.rs +@@ -800,6 +800,7 @@ + use solidcraft_render::job::{CpuProgressiveOptions, ImageRequest, JobOptions, RaytraceOptions}; + let (session, host) = native().unwrap(); + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/gpu/src/path/denoise_tests.rs ++++ b/crates/gpu/src/path/denoise_tests.rs +@@ -157,6 +157,7 @@ + let mut camera = Camera { distance: 4.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/gpu/src/path/tests.rs ++++ b/crates/gpu/src/path/tests.rs +@@ -21,6 +21,7 @@ + let mut camera = Camera { distance: 4.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -434,6 +435,7 @@ + let bounds = meshes.iter().fold(Aabb3::EMPTY, |a, m| a.union(&m.mesh.bounds())); + let camera = Camera { target: Vec3::new(0.0, 0.0, 1.0), yaw: -0.45, pitch: 0.5, distance: 13.0, fov: 0.65, ..Default::default() }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/examples/cpu_resource_smoke.rs ++++ b/crates/render/examples/cpu_resource_smoke.rs +@@ -31,6 +31,7 @@ + let mut camera = Camera { distance: 65.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/host.rs ++++ b/crates/render/src/job/host.rs +@@ -188,6 +188,7 @@ + strip.append_to(&mut options, 64)?; + } + Ok(ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -1183,7 +1184,7 @@ + if let Some(partial) = self.partial.as_mut() { + let partial = partial.get_mut()?; + let task = self.task.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; +- let uniform_pass = task.completed_pass_ready(partial.credits.plan)?; ++ let uniform_pass = if self.handle.0.request.cpu_progressive_every_pass { task.completed_pass_ready(partial.credits.plan)? } else { None }; + let automatic_pass = uniform_pass.filter(|pass| *pass > partial.last_pass_attempt); + if let Some(pass) = automatic_pass { + partial.last_pass_attempt = pass; +@@ -1383,10 +1384,12 @@ + data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; + self.handle.0.cancel.check()?; + } +- self.next_checkpoint_pass = self +- .next_checkpoint_pass +- .checked_add(1) +- .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; ++ self.next_checkpoint_pass = if self.handle.0.request.cpu_progressive_every_pass { ++ self.next_checkpoint_pass.checked_add(1) ++ } else { ++ self.next_checkpoint_pass.checked_mul(2) ++ } ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; + let Some(reservation) = reservation else { + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips +@@ -1656,7 +1659,7 @@ + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require CPU progressive intent"))? + .samples_per_pixel; +- let plan = super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())?; ++ let plan = super::ProtectedPreviewPlan::with_cadence(request.width, request.height, samples, request.cpu_budget(), request.cpu_progressive_every_pass)?; + Ok(CpuPreviewPolicy::Protected(plan)) + } + +@@ -1742,7 +1745,7 @@ + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require a progressive sample target"))? + .samples_per_pixel; + protected.validate()?; +- if protected != super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())? { ++ if protected != super::ProtectedPreviewPlan::with_cadence(request.width, request.height, samples, request.cpu_budget(), request.cpu_progressive_every_pass)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan does not match its admitted request")); + } + } +@@ -2159,6 +2162,7 @@ + ) + .map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -2390,6 +2394,7 @@ + let mut lights = Vec::with_capacity(8); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -2464,6 +2469,7 @@ + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -2581,6 +2587,7 @@ + + fn request() -> ImageRequest { + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/host_regrade_tests.rs ++++ b/crates/render/src/job/host_regrade_tests.rs +@@ -47,6 +47,7 @@ + let begins = Arc::new(AtomicUsize::new(0)); + let host = ImageHost::cooperative_with(Arc::new(FixtureExecutor(begins.clone()))); + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/host_tests.rs ++++ b/crates/render/src/job/host_tests.rs +@@ -546,6 +546,90 @@ + (host, job, running) + } + ++ fn fixture_with_cadence(samples: u32, every_pass: bool) -> (CpuHost, JobHandle, Running) { ++ let host = ImageHost(Arc::new(Owner { ++ executor: None, ++ shared: CpuHost::shared(MEMORY_LIMIT), ++ kind: HostKind::NativeWorker, ++ running: Mutex::new(None), ++ _worker: None, ++ })); ++ let request = ImageRequest { ++ cpu_progressive_every_pass: every_pass, ++ integrator: Integrator::Raytrace, ++ raytrace: Some(RaytraceOptions { ++ progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 123 }), ++ lights: Some(Vec::new()), ++ ..Default::default() ++ }), ++ width: 4, ++ height: 4, ++ ..request() ++ }; ++ let expected = admit(&empty(), &request).unwrap().estimated_total_bytes; ++ let job = host.submit(id(7300, 1), 19, empty(), request).unwrap(); ++ assert_eq!(host.admitted_bytes(), expected); ++ let work = host.0.shared.queue.lock().unwrap().pop_front().unwrap(); ++ let running = Running::begin(work).unwrap(); ++ (host, job, running) ++ } ++ ++ #[test] ++ fn captured_legacy_cadence_reaches_real_worker_checkpoints_and_keeps_final_bytes_identical() { ++ for (target, sparse) in [(3, vec![1, 2]), (5, vec![1, 2, 4]), (9, vec![1, 2, 4, 8])] { ++ let mut baseline: Option> = None; ++ for every_pass in [true, false] { ++ let (host, job, mut running) = fixture_with_cadence(target, every_pass); ++ let mut samples = Vec::new(); ++ let mut last_sequence = 0; ++ let mut complete = false; ++ for _ in 0..100_000 { ++ let more = running.advance(1).unwrap(); ++ if let Some(preview) = job.preview().unwrap() ++ && preview.info.frame_sequence != last_sequence ++ { ++ last_sequence = preview.info.frame_sequence; ++ samples.push(preview.info.samples_per_pixel); ++ } ++ assert_eq!(job.status().unwrap().request.cpu_progressive_every_pass, every_pass); ++ if !more { ++ complete = true; ++ break; ++ } ++ } ++ assert!(complete); ++ assert_eq!(samples, if every_pass { (1..target).collect::>() } else { sparse.clone() }); ++ assert_eq!(job.status().unwrap().cpu_preview_retention_skips, 0); ++ let frame = job.frame().unwrap().unwrap(); ++ if let Some(expected) = &baseline { ++ assert_eq!(frame.png(), expected.as_slice()); ++ } else { ++ baseline = Some(frame.png().to_vec()); ++ } ++ assert_eq!(job.status().unwrap().progress.phase, Phase::Completed); ++ drop(frame); ++ drop(running); ++ drop(job); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++ } ++ } ++ ++ #[test] ++ fn legacy_cadence_cancellation_during_hashing_cannot_publish_or_release_a_live_payload_early() { ++ let (host, job, mut running) = fixture_with_cadence(9, false); ++ before_preview(&mut running); ++ assert!(running.pending_png.is_some()); ++ job.cancel().unwrap(); ++ assert!(!running.guarded_step(1)); ++ assert_eq!(job.status().unwrap().progress.phase, Phase::Cancelled); ++ assert!(job.preview().unwrap().is_none()); ++ assert!(job.frame().unwrap().is_none()); ++ drop(running); ++ drop(job); ++ assert_eq!(host.admitted_bytes(), 0); ++ } ++ + fn before_preview(running: &mut Running) { + for _ in 0..100_000 { + if running.pending_png.as_ref().is_some_and(|p| p.preview_samples.is_some()) { +@@ -655,6 +739,7 @@ + + fn request() -> ImageRequest { + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/image_tests.rs ++++ b/crates/render/src/job/image_tests.rs +@@ -98,6 +98,7 @@ + let mut camera = Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Front); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -860,3 +861,55 @@ + assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (8, 8)); + } + } ++ ++#[test] ++fn captured_cpu_preview_cadence_roundtrips_without_saved_sampling_or_nested_aliases() { ++ let mut input = request(); ++ input.integrator = super::super::Integrator::Raytrace; ++ input.transparent_background = false; ++ input.raytrace = Some(super::super::RaytraceOptions { ++ progressive: Some(super::super::CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 }), ++ ..Default::default() ++ }); ++ for every_pass in [true, false] { ++ input.cpu_progressive_every_pass = every_pass; ++ let wire = serde_json::to_value(&input).unwrap(); ++ assert_eq!(wire.get("cpu_progressive_every_pass"), (!every_pass).then_some(&serde_json::Value::Bool(false))); ++ assert!(wire["raytrace"].get("cpu_progressive_every_pass").is_none()); ++ let decoded: ImageRequest = serde_json::from_value(wire).unwrap(); ++ assert_eq!(decoded.cpu_progressive_every_pass, every_pass); ++ assert_eq!(decoded.raytrace.as_ref().unwrap().progressive, input.raytrace.as_ref().unwrap().progressive); ++ assert_eq!(decoded.try_clone_for_host().unwrap().cpu_progressive_every_pass, every_pass); ++ } ++} ++ ++#[cfg(feature = "raytrace-cpu")] ++#[test] ++fn legacy_protected_feedback_restores_the_original_global_distribution_and_sixty_four_cap() { ++ use super::super::{CpuBudget, ProtectedPreviewPlan}; ++ let tiny = ProtectedPreviewPlan::with_cadence(2, 1, 5, CpuBudget::Compact, false).unwrap(); ++ assert_eq!(tiny.quota_limit(), 9); ++ assert_eq!((0..9).map(|index| tiny.milestone(index).unwrap()).collect::>(), [1, 2, 3, 4, 5, 6, 7, 8, 9]); ++ let plan = ProtectedPreviewPlan::with_cadence(65, 1, 3, CpuBudget::Compact, false).unwrap(); ++ plan.validate().unwrap(); ++ assert_eq!(plan.quota_limit(), 64); ++ assert_eq!([0, 1, 31, 32, 63].map(|index| plan.milestone(index).unwrap()), [1, 4, 95, 99, 194]); ++ let milestones: Vec<_> = (0..64).map(|index| plan.milestone(index).unwrap()).collect(); ++ for committed in 0..=195 { ++ let expected = milestones.iter().filter(|&&milestone| milestone <= committed).count() as u32; ++ assert_eq!(plan.reached_milestones(committed).unwrap(), expected); ++ } ++ assert!(plan.reached_milestones(196).is_err()); ++ assert!(plan.milestone(64).is_err()); ++ assert_eq!(plan.presentation_limit().unwrap(), 64 * plan.snapshot_work().unwrap()); ++ assert_eq!(plan.ordinary_limit(), CpuBudget::Compact.limits().max_work_units); ++ let single = ProtectedPreviewPlan::with_cadence(1, 1, 1, CpuBudget::Compact, false).unwrap(); ++ assert_eq!((single.quota_limit(), single.reached_milestones(1).unwrap()), (0, 0)); ++ let one = ProtectedPreviewPlan::with_cadence(1, 1, 2, CpuBudget::Compact, false).unwrap(); ++ assert_eq!((one.quota_limit(), one.milestone(0).unwrap(), one.reached_milestones(1).unwrap()), (1, 1, 1)); ++ let high = ProtectedPreviewPlan::with_cadence(1, 1, 1_048_576, CpuBudget::Workstation, false).unwrap(); ++ assert_eq!((high.quota_limit(), high.milestone(63).unwrap()), (64, 1_048_575)); ++ assert_eq!(high.reached_milestones(1_048_576).unwrap(), 64); ++ let current = ProtectedPreviewPlan::new(65, 1, 3, CpuBudget::Compact).unwrap(); ++ assert_eq!(current.quota_limit(), 66); ++} +--- a/crates/render/src/job/led_strip/tests.rs ++++ b/crates/render/src/job/led_strip/tests.rs +@@ -192,6 +192,7 @@ + let mut camera = Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/mod.rs ++++ b/crates/render/src/job/mod.rs +@@ -1118,6 +1118,10 @@ + #[derive(Clone, Debug, Serialize, Deserialize)] + #[serde(deny_unknown_fields)] + pub struct ImageRequest { ++ /// Captured CPU publication policy, separate from saved sampling intent. ++ /// False survives request serialization; omission preserves every-pass mode. ++ #[serde(default = "default_cpu_progressive_every_pass", skip_serializing_if = "cpu_progressive_every_pass_enabled")] ++ pub cpu_progressive_every_pass: bool, + /// Resolved Raster-only capture of RenderSetup.exposure_ev, never a second authority. + #[serde(default, skip_serializing_if = "zero_raster_exposure")] + pub raster_exposure_ev: f64, +@@ -1160,6 +1164,14 @@ + Straight, + } + ++fn default_cpu_progressive_every_pass() -> bool { ++ true ++} ++ ++fn cpu_progressive_every_pass_enabled(value: &bool) -> bool { ++ *value ++} ++ + impl ImageRequest { + pub fn has_local_raster_lights(&self) -> bool { + self.raster_punctual_lights.is_some() || self.raster_area_lights.is_some() +@@ -1234,6 +1246,7 @@ + return Ok(self.clone()); + } + Ok(Self { ++ cpu_progressive_every_pass: self.cpu_progressive_every_pass, + raster_exposure_ev: self.raster_exposure_ev, + raster_lights: raster_lights::try_copy(&self.raster_lights)?, + raster_punctual_lights: raster_lights::try_copy_punctual(&self.raster_punctual_lights)?, +@@ -1771,6 +1784,7 @@ + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct ProtectedPreviewPlan { + preview: PartialPreviewPlan, ++ every_pass: bool, + samples_per_pixel: u32, + budget: CpuBudget, + total_commits: u64, +@@ -1778,6 +1792,9 @@ + } + impl ProtectedPreviewPlan { + pub fn new(source_width: u32, source_height: u32, samples_per_pixel: u32, budget: CpuBudget) -> Result { ++ Self::with_cadence(source_width, source_height, samples_per_pixel, budget, true) ++ } ++ pub(crate) fn with_cadence(source_width: u32, source_height: u32, samples_per_pixel: u32, budget: CpuBudget, every_pass: bool) -> Result { + budget.validate_image(source_width, source_height, Some(CpuProgressiveOptions { samples_per_pixel, seed: 0 }))?; + let preview = PartialPreviewPlan::new(source_width, source_height)?; + let total_commits = u64::from(source_width) +@@ -1787,14 +1804,17 @@ + let pixels = u64::from(source_width) * u64::from(source_height); + let early = + u32::try_from(pixels.saturating_sub(1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early quota overflow"))?; +- let quota_limit = +- early.checked_add(samples_per_pixel - 1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))?; +- let plan = Self { preview, samples_per_pixel, budget, total_commits, quota_limit }; ++ let quota_limit = if every_pass { ++ early.checked_add(samples_per_pixel - 1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))? ++ } else { ++ u32::try_from(total_commits.saturating_sub(1).min(64)).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected quota overflow"))? ++ }; ++ let plan = Self { preview, every_pass, samples_per_pixel, budget, total_commits, quota_limit }; + plan.aggregate_limit()?; + Ok(plan) + } + pub fn validate(&self) -> Result<()> { +- if *self != Self::new(self.preview.source_width(), self.preview.source_height(), self.samples_per_pixel, self.budget)? { ++ if *self != Self::with_cadence(self.preview.source_width(), self.preview.source_height(), self.samples_per_pixel, self.budget, self.every_pass)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan differs from its canonical policy")); + } + Ok(()) +@@ -1838,6 +1858,20 @@ + pub(crate) fn reached_milestones(&self, committed: u64) -> Result { + if committed > self.total_commits { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected frontier exceeds its final target")); ++ } ++ if !self.every_pass { ++ if committed == 0 || self.quota_limit == 0 { ++ return Ok(0); ++ } ++ if committed >= self.total_commits - 1 || self.quota_limit == 1 { ++ return Ok(self.quota_limit); ++ } ++ return committed ++ .checked_mul(u64::from(self.quota_limit - 1)) ++ .map(|n| n.div_ceil(self.total_commits - 2)) ++ .and_then(|n| u32::try_from(n).ok()) ++ .filter(|n| *n <= self.quota_limit) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected legacy reached quota overflow")); + } + let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); + let early = pixels.saturating_sub(1).min(64); +@@ -1866,6 +1900,17 @@ + if index >= self.quota_limit { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected milestone index outside its quota")); + } ++ if !self.every_pass { ++ if self.quota_limit == 1 { ++ return Ok(1); ++ } ++ return self.total_commits ++ .checked_sub(2) ++ .and_then(|n| n.checked_mul(u64::from(index))) ++ .and_then(|n| n.checked_div(u64::from(self.quota_limit - 1))) ++ .and_then(|n| n.checked_add(1)) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "protected legacy milestone overflow")); ++ } + let pixels = u64::from(self.preview.source_width()) * u64::from(self.preview.source_height()); + let early = u32::try_from(pixels.saturating_sub(1).min(64)) + .map_err(|_| JobError::new(ErrorCode::LimitExceeded, "protected early milestone overflow"))?; +--- a/crates/render/src/job/png.rs ++++ b/crates/render/src/job/png.rs +@@ -104,6 +104,7 @@ + + fn request(width: u32, height: u32) -> ImageRequest { + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/regrade.rs ++++ b/crates/render/src/job/regrade.rs +@@ -94,6 +94,7 @@ + return self.pending(done, total); + } + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -180,6 +181,7 @@ + } + self.linear = None; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/job/rt2_tests.rs ++++ b/crates/render/src/job/rt2_tests.rs +@@ -6,6 +6,7 @@ + + fn request(integrator: Integrator) -> ImageRequest { + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/anisotropic_faces_tests.rs ++++ b/crates/render/src/raytrace/anisotropic_faces_tests.rs +@@ -146,6 +146,7 @@ + fn decoded_cpu_png_rotates_only_the_two_explicit_planar_targets() { + fn render(scene: ProductScene, camera: Camera, options: RaytraceOptions) -> ::image::RgbaImage { + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs ++++ b/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs +@@ -64,6 +64,7 @@ + ..Default::default() + }; + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/deterministic_primary_tests.rs ++++ b/crates/render/src/raytrace/deterministic_primary_tests.rs +@@ -64,6 +64,7 @@ + ..Default::default() + }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -233,6 +234,7 @@ + ..Default::default() + }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/dielectric_tests.rs ++++ b/crates/render/src/raytrace/dielectric_tests.rs +@@ -43,6 +43,7 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/environment_image_tests.rs ++++ b/crates/render/src/raytrace/environment_image_tests.rs +@@ -35,6 +35,7 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/environment_reflection_tests.rs ++++ b/crates/render/src/raytrace/environment_reflection_tests.rs +@@ -40,6 +40,7 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/image.rs ++++ b/crates/render/src/raytrace/image.rs +@@ -171,7 +171,7 @@ + plan.validate()?; + let progressive = + options.progressive.ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected feedback requires progressive CPU sampling"))?; +- if plan != job::ProtectedPreviewPlan::new(request.width, request.height, progressive.samples_per_pixel, options.budget)? { ++ if plan != job::ProtectedPreviewPlan::with_cadence(request.width, request.height, progressive.samples_per_pixel, options.budget, request.cpu_progressive_every_pass)? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan differs from actual source sampling or budget")); + } + } +@@ -2192,13 +2192,13 @@ + if self.pixel == self.request.width as usize * self.request.height as usize { + if let Some(progressive) = &mut self.progressive { + let samples = progressive.film.samples(); +- if progressive.partial_plan.is_some() && samples < progressive.options.samples_per_pixel && samples > self.last_pass_boundary ++ if self.request.cpu_progressive_every_pass && progressive.partial_plan.is_some() && samples < progressive.options.samples_per_pixel && samples > self.last_pass_boundary + { + self.last_pass_boundary = samples; + return Ok(ImageAdvance::Legacy(ImagePoll::Pending(self.progress()))); + } + self.work.tick(&self.cancel).map_err(error)?; +- if samples == progressive.options.samples_per_pixel || progressive.partial_plan.is_none() { ++ if samples == progressive.options.samples_per_pixel || (progressive.partial_plan.is_none() && (self.request.cpu_progressive_every_pass || samples.is_power_of_two())) { + progressive.resolving = true; + } else { + self.pixel = 0; +--- a/crates/render/src/raytrace/image_tests.rs ++++ b/crates/render/src/raytrace/image_tests.rs +@@ -176,6 +176,7 @@ + } + fn request() -> ImageRequest { + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -3127,6 +3128,7 @@ + ..Default::default() + }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/primary_aa_tests.rs ++++ b/crates/render/src/raytrace/primary_aa_tests.rs +@@ -178,6 +178,7 @@ + ..Default::default() + }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -781,6 +782,7 @@ + ..Default::default() + }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -1978,3 +1980,52 @@ + assert_eq!(bits, [[0.0_f64.to_bits(); 3]]); + assert!(task.done && task.progressive.is_none()); + } ++ ++#[test] ++fn sparse_checkpoint_compatibility_preserves_each_final_png_and_deterministic_sample_prefix() { ++ for (target, expected_sparse) in [(1, vec![]), (3, vec![1, 2]), (5, vec![1, 2, 4]), (9, vec![1, 2, 4, 8])] { ++ let current = progressive_fixture(target, 19, Some(true), 1.0); ++ let source = current.visibility_owner.source().clone(); ++ let options = current.visibility_owner.options().clone(); ++ let mut legacy_request = current.request.clone(); ++ legacy_request.cpu_progressive_every_pass = false; ++ let legacy = ImageTask::new(source, legacy_request, CancelToken::default(), options).unwrap(); ++ let (each_previews, each_final, _) = progressive_complete(current, 1); ++ let (legacy_previews, legacy_final, _) = progressive_complete(legacy, 3); ++ assert_eq!(each_previews.iter().map(|(samples, _)| *samples).collect::>(), (1..target).collect::>()); ++ assert_eq!(legacy_previews.iter().map(|(samples, _)| *samples).collect::>(), expected_sparse); ++ assert_eq!(legacy_final, each_final, "publication policy must not change the requested final PNG"); ++ for (samples, png) in legacy_previews { ++ assert_eq!(png, each_previews.iter().find(|(count, _)| *count == samples).unwrap().1); ++ } ++ } ++} ++ ++#[test] ++fn legacy_protected_producer_consumes_the_original_global_milestones_without_changing_final_pixels() { ++ let (scene, mut request, options) = partial_four_pixel_source(5, 29); ++ request.cpu_progressive_every_pass = false; ++ let reference = ImageTask::new(scene.clone(), request.clone(), CancelToken::default(), options.clone()).unwrap(); ++ let (_, expected_png, _) = progressive_complete(reference, 3); ++ let plan = job::ProtectedPreviewPlan::with_cadence(request.width, request.height, 5, options.budget, false).unwrap(); ++ assert_eq!((plan.total_commits(), plan.quota_limit()), (20, 19)); ++ let mut task = ImageTask::new_with_environment_and_nested_and_protected_partial( ++ scene, request, CancelToken::default(), options, None, false, plan, ++ ) ++ .unwrap(); ++ let mut rays = Vec::new(); ++ for committed in 1..20 { ++ reach_partial_frontier(&mut task, (committed / 4) as u32, (committed % 4) as usize, &mut rays); ++ assert!(matches!(task.begin_partial_preview(plan.preview_plan()).unwrap(), PartialBegin::Started)); ++ let (_, _, passes, prefix) = finish_partial_snapshot(&mut task); ++ assert_eq!(u64::from(passes) * 4 + prefix, committed); ++ let report = task.protected_preview_report().unwrap(); ++ assert_eq!((report.accepted_snapshots, report.next_milestone_index), (committed as u32, committed as u32)); ++ assert_eq!(report.quota_limit, 19); ++ } ++ let (actual_png, _) = finish_partial_final(&mut task, true, &mut rays); ++ assert_eq!(actual_png, expected_png); ++ let report = task.protected_preview_report().unwrap(); ++ assert_eq!((report.accepted_snapshots, report.quota_limit), (19, 19)); ++ assert_eq!(report.presentation_used, 19 * plan.snapshot_work().unwrap()); ++} +--- a/crates/render/src/raytrace/punctual_image_tests.rs ++++ b/crates/render/src/raytrace/punctual_image_tests.rs +@@ -44,6 +44,7 @@ + ..Default::default() + }; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/render/src/raytrace/reflection_image_tests.rs ++++ b/crates/render/src/raytrace/reflection_image_tests.rs +@@ -183,6 +183,7 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Front); + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/core/source-bindings.json b/proposals/render/2026-10-31/progressive-compatibility-wip/core/source-bindings.json new file mode 100644 index 000000000..60925e765 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/core/source-bindings.json @@ -0,0 +1,192 @@ +{ + "status": "SOURCE_ONLY_NOT_ADOPTED_UNCOMPILED_UNRUN", + "subpackage": "core", + "base_source_manifest_sha256": "d38a8d946b6653864ad8918d4da662725bd24ca01b2e5aa2d3b38b47b1a7e163", + "base_rule": "Exact per-file RAW preimages only. Not current main, not a combined candidate. LF patch is review aid; RAW candidate bytes are authoritative.", + "files": [ + { + "path": "crates/engine/src/cmd/render.rs", + "before_sha256": "13d0bc2e8a72589e0b7a6cad8a6d04d8a22d53196341be8ae6826afaf48584fa", + "before_bytes": 44175, + "after_sha256": "bcf237b491702c72b39fc6785cd5b2ea122f56bab150ba453890162e5bee4c2c", + "after_bytes": 44454 + }, + { + "path": "crates/engine/src/cmd/render/jobs.rs", + "before_sha256": "2047f85079cb63cb5f7707132547495bf04b6ec445ddd5579bfb3e8df2223720", + "before_bytes": 80469, + "after_sha256": "2fc9237027d138156680a706ba7b21c053e482e315a6853628baaf86719b4a48", + "after_bytes": 85636 + }, + { + "path": "crates/engine/src/render_jobs.rs", + "before_sha256": "27aa67247bbd57610432caf62bfc51af25fcd51c8827c41df99f12bd1aa74666", + "before_bytes": 42460, + "after_sha256": "0dd214ab6a8b0008c5246c06a104486e9c688d4b83cbf9b528f48dff4c115e8f", + "after_bytes": 42506 + }, + { + "path": "crates/gpu/src/path/denoise_tests.rs", + "before_sha256": "011bf8457c8fbfa4409ab5469d16472371112c9a68e1500d4d4c652e93f474e0", + "before_bytes": 15894, + "after_sha256": "6c7cae223c6f1bdba7dead425c2f7071f9ca9c8e0c93f356283162471f784105", + "after_bytes": 15936 + }, + { + "path": "crates/gpu/src/path/tests.rs", + "before_sha256": "206f281b911227041f1a9fdb882e6258f6ee2cd474eecb8437334c1712e3be2b", + "before_bytes": 164444, + "after_sha256": "bd688f029e4a63294dfa8d5609c7a495fbf9978b6ec6f77faa43661a30ae9ad1", + "after_bytes": 164528 + }, + { + "path": "crates/render/examples/cpu_resource_smoke.rs", + "before_sha256": "962ec3c205a4a0203a2822654c3000493ce44ea19122b6dbe8be4c07fc28b6a1", + "before_bytes": 8548, + "after_sha256": "992849c3c2d6c67580539d43d95893cc4bf296f7906b406159f1fd74d5e9e45b", + "after_bytes": 8590 + }, + { + "path": "crates/render/src/job/host.rs", + "before_sha256": "9dbf55511147641a8d7d7c3b4bf444ae8b8ece154aab49db4b57cb208347b4a8", + "before_bytes": 135424, + "after_sha256": "89f289616278f62ac71974df1edb8890ccf910be0307aa2dbb043b82b7eda4a7", + "after_bytes": 135938 + }, + { + "path": "crates/render/src/job/host_regrade_tests.rs", + "before_sha256": "f4bd4bd1216ff356691e99a911a110f43bde624cb4544281c9a521b27067d762", + "before_bytes": 7156, + "after_sha256": "264c69d6a247c1bed7f309d6f13ed38ee18927671db0642fa8dddab71566098f", + "after_bytes": 7198 + }, + { + "path": "crates/render/src/job/host_tests.rs", + "before_sha256": "f159bd988beb8055b7d6e80a89eef5ba1e967e982c97d5480b80c93d19509ef0", + "before_bytes": 119544, + "after_sha256": "455d87a8573e0438b506be62710a3473d30d112151afab6de3ff6cb98c09223a", + "after_bytes": 123326 + }, + { + "path": "crates/render/src/job/image_tests.rs", + "before_sha256": "8b8f84e21ded158040c697f9491b6afbf7ab01c5759becee61e56f2606518454", + "before_bytes": 43963, + "after_sha256": "ed0781fa45aa08be62f2d230f4ed53602e4de9e21ba25021ea81687b6db6b218", + "after_bytes": 47200 + }, + { + "path": "crates/render/src/job/led_strip/tests.rs", + "before_sha256": "8788bd088b5baab8a0ef6bd8026cf8d5c4eadfc53b8f3e1cf1ca32cc1b6fa828", + "before_bytes": 11810, + "after_sha256": "233782eb6b0ff5f08b054aa1252d56f977e9ecd72b99178fa52cb0941927972e", + "after_bytes": 11856 + }, + { + "path": "crates/render/src/job/mod.rs", + "before_sha256": "ad442c55f9a3edeeac359ca4c91c2dc5028bee36b981f6953e6399daf65c7c12", + "before_bytes": 84674, + "after_sha256": "ec10cd33a59211b63d47895590b995c7a9fdaa6da0f987faf84cc2cc172c1027", + "after_bytes": 86849 + }, + { + "path": "crates/render/src/job/png.rs", + "before_sha256": "40abe173012f2be59f515517b3e89bbe530d2275f4d6f8b40cbd9686d76c84fd", + "before_bytes": 7403, + "after_sha256": "4c1ce7363e38315be32b9018f4b0c92450909be5e64b64d85b2f126904e705d5", + "after_bytes": 7449 + }, + { + "path": "crates/render/src/job/regrade.rs", + "before_sha256": "5a3d7e3079d5ba1c553b07f8f845876424d6488229baefbcbbc25048b5651a16", + "before_bytes": 9698, + "after_sha256": "966a4460bbca2e1d800103accaa28fbbc58d2775ff128132169d21de839fc545", + "after_bytes": 9794 + }, + { + "path": "crates/render/src/job/rt2_tests.rs", + "before_sha256": "8f0c3a3d476c55935367dc95604d02d16d9235beed4ab2e1aa65700cce83b51b", + "before_bytes": 12445, + "after_sha256": "7e7b3fd7edfd30ae1ca11ce37eb82ff637a1302cec1d5c7991a60cf648e4e61d", + "after_bytes": 12487 + }, + { + "path": "crates/render/src/raytrace/anisotropic_faces_tests.rs", + "before_sha256": "b63e1d323aacc2eeea1056a332ada92df78a78ef52b8c2aee5313e064d8cc479", + "before_bytes": 11516, + "after_sha256": "79eabb6c302a2cc38adb20be1151ec2b307ba21eda0dc39082ba6f9e39b53186", + "after_bytes": 11562 + }, + { + "path": "crates/render/src/raytrace/anisotropic_reflection_image_tests.rs", + "before_sha256": "8039e47fd0442f9620065ba180dbec7771bf4c0b606d12d66de3e5e63e1d0b52", + "before_bytes": 13853, + "after_sha256": "28a93efcdd8e237e5148e70a298e01b66b88572a309d9e077d38d967bfca15f4", + "after_bytes": 13895 + }, + { + "path": "crates/render/src/raytrace/deterministic_primary_tests.rs", + "before_sha256": "0fb5830cce4c9b88fe133000f4338041712880793ea7ed897a854a7f1b9a7675", + "before_bytes": 26656, + "after_sha256": "19e8f7161648e28938ac6e4b779a0ff420b9cb5a5251245b70f9f5532c1ffedc", + "after_bytes": 26740 + }, + { + "path": "crates/render/src/raytrace/dielectric_tests.rs", + "before_sha256": "6bdea1646422e925ca071b7e1643af1a9bc4c5125ad0abb69bfed17716ba64ca", + "before_bytes": 57132, + "after_sha256": "07a5fae9a8d1da52f6d26f9781073e91bcbea5b3143de6cd609f554165f20acd", + "after_bytes": 57174 + }, + { + "path": "crates/render/src/raytrace/environment_image_tests.rs", + "before_sha256": "42442aaa4bcdda016b4349e096fd389e731df13683dbef9938925298432912b9", + "before_bytes": 14637, + "after_sha256": "62b0ebac6e9e6a331b1866d1fca9a0e804b51189c980ff4e861e4443bfa62bce", + "after_bytes": 14679 + }, + { + "path": "crates/render/src/raytrace/environment_reflection_tests.rs", + "before_sha256": "1466b408dd3e670ce05ae3cb0487e789c77a7079ad88093d83c70f4de4cb7d75", + "before_bytes": 12619, + "after_sha256": "1be638c140d841d32549de3bfba78615c51a9d63b52e7a4f7e285bff2d97b225", + "after_bytes": 12661 + }, + { + "path": "crates/render/src/raytrace/image.rs", + "before_sha256": "4e8f63765ca35f305e3caa0946fceba90573be243717bd08b54deeb948f59326", + "before_bytes": 126260, + "after_sha256": "06c517a1827fd53d3f3f0b22d927c5dbcc005c32fd7b556f45ab51ce049ee4e1", + "after_bytes": 126424 + }, + { + "path": "crates/render/src/raytrace/image_tests.rs", + "before_sha256": "5e6724dfe01a583b880862e24a2bfada40052bda09388e977f28f70f55029f89", + "before_bytes": 173358, + "after_sha256": "68ff49f05ab005fa9a8540660f97fedbef637b79c2cb02129ee7f358394b6609", + "after_bytes": 173446 + }, + { + "path": "crates/render/src/raytrace/primary_aa_tests.rs", + "before_sha256": "9366a35fa85e3b04eca01438da697979a1be4528fbc57a21d13da4b69aa175fc", + "before_bytes": 98436, + "after_sha256": "8b728f4c2d8f33dd50a78e93e3328907213e6419e3a84c8403aea4e02b909551", + "after_bytes": 101590 + }, + { + "path": "crates/render/src/raytrace/punctual_image_tests.rs", + "before_sha256": "fc07b7dbfb3996952d8c9ad55aa228a4bb4740ec5703bc6a5a551c7657f66394", + "before_bytes": 11513, + "after_sha256": "0099c88b7982ef8d295cc86d5e56ddc2a814ef405cb0ce0a235149d1e904a870", + "after_bytes": 11555 + }, + { + "path": "crates/render/src/raytrace/reflection_image_tests.rs", + "before_sha256": "87d80555bea2bf2e908f20223796f6d58d59508f13a930aa9e11eb36e6d999de", + "before_bytes": 15596, + "after_sha256": "568a111b43726ff10c98d75c6363360ccadd18cde964bd5192b06aff29c62936", + "after_bytes": 15638 + } + ], + "full_CI_native_or_readiness": false, + "candidate_whole_file_overlay_safe": true +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/README.md b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/README.md new file mode 100644 index 000000000..0762454e5 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/README.md @@ -0,0 +1,22 @@ +# Exact earlier C28 formatted host, separate from compatibility WIP + +This is the actual compiled C28 host source (RAW SHA-256 +9dbf55511147641a8d7d7c3b4bf444ae8b8ece154aab49db4b57cb208347b4a8), +retained as the before file in the sealed compatibility core packet. It belongs +to the C28 d38a exact-source baseline. The formatter removed exactly one LF +from the prior recovery source 2c72c307; every other byte is unchanged. + +Earlier C28 built five library artifacts and completed ten inventories. Selected +cases: **28 PASS / 1 font-fixture panic / 954 UNRUN**, with two actual +CPU-supported true markers before stopping. Postchecks were not executed; no +native application acceptance, full CI or readiness is claimed. This single file +is not the whole source binding for that earlier build. + +The failure was case 976's unregistered ui-semibold test font, not a failing +SPP/cap assertion. Its before test-file SHA is 28ddafe4; that exact source is +already preserved in the [earlier source archive](../../cpu-every-pass-c27-source/candidate/crates/ui-egui/src/render_workspace_tests.rs). +The separate fontfix candidate 9a3e58d8 is UNRUN and must not inherit a pass here. + +Do not confuse this file with core's compatibility host candidate 89f28961, +which remains NOT ADOPTED, UNCOMPILED and UNRUN. No compatibility code is applied +by this reference package. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/candidate/crates/render/src/job/host.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/candidate/crates/render/src/job/host.rs new file mode 100644 index 000000000..914470727 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/candidate/crates/render/src/job/host.rs @@ -0,0 +1,2992 @@ +//! Caller-owned image execution host. One worker, two bounded queued inputs; browser pumping +//! uses the same incremental task without threads. Shared ownership never includes CAD state. + +use std::collections::VecDeque; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Condvar; +use std::sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, AtomicU64, Ordering}, +}; + +use serde::Serialize; +use sha2::{Digest, Sha256}; + +use super::{ + Admission, AlphaConvention, CancelToken, ColourEncoding, ErrorCode, FrameInfo, ImageExecutor, ImageRequest, ImageTask, ImageWork, Integrator, + JobError, JobId, JobOptions, Phase, Progress, Result, TaskPoll, admit, +}; +use crate::{ + Availability, ExecutorDescriptor, ExecutorId, ProductScene, RenderFormat, RenderLimits, RenderMode, RenderOperation, RenderProfile, ScratchLayout, +}; + +const MEMORY_LIMIT: u64 = 512 * 1024 * 1024; +const QUEUE_LIMIT: usize = 2; + +#[cfg(test)] +struct CpuExecutor; +#[cfg(test)] +impl ImageExecutor for CpuExecutor { + fn descriptor(&self) -> Result { + Ok(ExecutorDescriptor { + id: ExecutorId::new("cpu-product").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: Availability::Available, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: vec![crate::RenderFeature::Pbr], + }], + limits: RenderLimits::default(), + scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }) + } + + fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + if options != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU product does not support sampling or exposure controls")); + } + admit(scene, request) + } + fn begin(&self, scene: ProductScene, request: ImageRequest, _options: JobOptions, cancel: CancelToken) -> Result> { + Ok(Box::new(ImageTask::new(scene, request, cancel)?)) + } +} + +// Completion notification precedes destruction of the worker's temporary handle. +// Lease tests join their owned, idle worker before checking exact retained bytes. +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +impl ImageHost { + pub(super) fn join_worker_for_test(&mut self) -> Result<()> { + self.0.shared.stop.store(true, Ordering::Release); + self.0.shared.wake.notify_all(); + let inner = Arc::get_mut(&mut self.0).ok_or_else(|| JobError::new(ErrorCode::Internal, "test must own its host"))?; + if let Some(worker) = inner._worker.take() { + worker.join().map_err(|_| JobError::new(ErrorCode::Internal, "test worker panicked"))?; + } + Ok(()) + } +} + +#[cfg(test)] +#[path = "host_regrade_tests.rs"] +mod regrade_tests; +#[cfg(test)] +#[path = "host_tests.rs"] +mod tests; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum HostKind { + NativeWorker, + Cooperative, +} + +struct Budget { + used: AtomicU64, + limit: u64, +} +pub(crate) struct Reservation { + budget: Arc, + bytes: u64, +} + +impl Budget { + fn reserve(self: &Arc, bytes: u64) -> Result { + let mut used = self.used.load(Ordering::Acquire); + loop { + let next = used.checked_add(bytes).filter(|n| *n <= self.limit).ok_or_else(|| { + JobError::new(ErrorCode::LimitExceeded, format!("image host admission pool is full ({} MiB)", self.limit / (1024 * 1024))) + })?; + match self.used.compare_exchange_weak(used, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break, + Err(current) => used = current, + } + } + Ok(Reservation { budget: self.clone(), bytes }) + } +} +impl Reservation { + /// Merge unique portions of one admission without a second pool debit. + fn merge_from(&mut self, donor: &mut Self) -> Result<()> { + if !Arc::ptr_eq(&self.budget, &donor.budget) { + return Err(JobError::new(ErrorCode::WrongOwner, "cannot merge different image admission pools")); + } + let bytes = self + .bytes + .checked_add(donor.bytes) + .filter(|v| *v <= self.budget.limit) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "image reservation merge overflow"))?; + self.bytes = bytes; + donor.bytes = 0; + Ok(()) + } + /// Transfer an already admitted portion without changing the pool's total. + /// CPU progressive admission includes every possible checkpoint up front. + fn split(&mut self, bytes: u64) -> Result { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "preview exceeds its prepaid reservation")); + } + self.bytes -= bytes; + Ok(Self { budget: self.budget.clone(), bytes }) + } + + pub(crate) fn shrink(&mut self, bytes: u64) -> Result<()> { + if bytes > self.bytes { + return Err(JobError::new(ErrorCode::LimitExceeded, "completed PNG exceeds its reservation")); + } + self.budget.used.fetch_sub(self.bytes - bytes, Ordering::AcqRel); + self.bytes = bytes; + Ok(()) + } +} +impl Drop for Reservation { + fn drop(&mut self) { + self.budget.used.fetch_sub(self.bytes, Ordering::AcqRel); + } +} + +/// Retained runtime input capacities survive work/PNG eviction through status handles. +fn retained_request_bytes(request: &ImageRequest) -> Result { + let existing = request.raytrace.as_ref().map_or(Ok(0), |options| options.retained_bytes())?; + existing + .checked_add(request.raster_lights_retained_bytes()?) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request size overflow")) +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod light_union_lease_tests { + use super::super::{DirectionalLightOptions, PunctualLightOptions, RaytraceOptions, led_strip::LedStripOptions}; + use super::*; + fn request() -> Result { + let mut options = RaytraceOptions { + primary_samples: 16, + lights: Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }; 8]), + punctual_lights: Some(vec![ + PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None + }; + 8 + ]), + ..Default::default() + }; + let strip = LedStripOptions { + center_mm: [0.0, 0.0, 10.0], + length_mm: 8.0, + width_mm: 0.5, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0; 3], + intensity: 2.0, + }; + for _ in 0..4 { + strip.append_to(&mut options, 64)?; + } + Ok(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: Integrator::Raytrace, + raytrace: Some(options), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }) + } + fn scene() -> ProductScene { + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY } + } + #[test] + fn normalized_union_uses_one_pool_and_keeps_record_lease_after_frame_eviction() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = request().unwrap(); + let bytes = retained_request_bytes(&request).unwrap(); + let capacities = request + .raytrace + .as_ref() + .map(|o| { + (o.lights.as_ref().unwrap().capacity(), o.punctual_lights.as_ref().unwrap().capacity(), o.area_lights.as_ref().unwrap().capacity()) + }) + .unwrap(); + let job = host.submit(JobId { session: 1724, serial: 1, generation: 1 }, 1, scene(), request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Synchronize this test's completed worker before asserting final Arc release; + // publication wakes waiters just before Running drops its temporary handle. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let retained = job.0.request.raytrace.as_ref().unwrap(); + assert_eq!( + capacities, + ( + retained.lights.as_ref().unwrap().capacity(), + retained.punctual_lights.as_ref().unwrap().capacity(), + retained.area_lights.as_ref().unwrap().capacity() + ) + ); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert!(host.admitted_bytes() > bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[test] + fn failed_union_metadata_reservation_releases_work_and_does_not_enqueue() { + let host = CpuHost::for_platform().unwrap(); + let request = request().unwrap(); + let work = admit(&scene(), &request).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let result = host.submit(JobId { session: 1724, serial: 2, generation: 1 }, 1, scene(), request); + assert_eq!(result.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } + + fn raster_local_pair() -> (ImageRequest, ProductScene) { + let mut input = request().unwrap(); + input.integrator = Integrator::Raster; + input.raytrace = None; + let mut points = Vec::with_capacity(8); + points.push(PunctualLightOptions { + position_mm: [0.0, 0.0, 10.0], + color: [1.0; 3], + intensity: 1.0, + reference_distance_mm: 10.0, + minimum_distance_mm: 0.001, + cone: None, + }); + let mut areas = Vec::with_capacity(4); + areas.push(super::super::RectangleLightOptions { + center_mm: [0.0, 0.0, 10.0], + edge_u_mm: [2.0, 0.0, 0.0], + edge_v_mm: [0.0, -2.0, 0.0], + color: [1.0; 3], + intensity: 1.0, + }); + input.raster_punctual_lights = Some(points); + input.raster_area_lights = Some(areas); + let mesh = solidcraft_geom::Mesh { + positions: vec![ + solidcraft_geom::Vec3::new(-2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(2.0, -2.0, 0.0), + solidcraft_geom::Vec3::new(0.0, 2.0, 0.0), + ], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + name: "Raster local lease fixture".into(), + mesh: Arc::new(mesh), + color: [160; 3], + opacity: 1.0, + surface: None, + transmission: None, + faces: Vec::new(), + }], + bounds, + }; + (input, scene) + } + + #[test] + fn raster_local_record_keeps_original_capacity_lease_after_real_completion_and_frame_drop() { + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let (input, scene) = raster_local_pair(); + let capacities = (input.raster_punctual_lights.as_ref().unwrap().capacity(), input.raster_area_lights.as_ref().unwrap().capacity()); + let bytes = (capacities.0 * std::mem::size_of::() + + capacities.1 * std::mem::size_of::()) as u64; + assert_eq!(retained_request_bytes(&input).unwrap(), bytes); + let job = host.submit(JobId { session: 1725, serial: 1, generation: 1 }, 1, scene, input).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + assert_eq!(job.0.request.raster_punctual_lights.as_ref().unwrap().capacity(), capacities.0); + assert_eq!(job.0.request.raster_area_lights.as_ref().unwrap().capacity(), capacities.1); + assert!(Arc::ptr_eq(&job.0._request_reservation.as_ref().unwrap().budget, &budget)); + assert_eq!(job.0._request_reservation.as_ref().unwrap().bytes, bytes); + let copied = job.status().unwrap().request; + assert_eq!(copied.raster_punctual_lights, job.0.request.raster_punctual_lights); + assert_eq!(copied.raster_area_lights, job.0.request.raster_area_lights); + drop(copied); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + drop(frame); + assert_eq!(host.admitted_bytes(), bytes); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), bytes); + drop(held); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + + #[test] + fn raster_local_metadata_reservation_failure_releases_work_without_enqueuing() { + let host = CpuHost::for_platform().unwrap(); + let (input, scene) = raster_local_pair(); + let work = host.admit(&scene, &input, JobOptions::default()).unwrap().estimated_total_bytes; + let fill = host.0.shared.budget.reserve(host.pool_limit_bytes() - work).unwrap(); + let before = host.admitted_bytes(); + let failed = host.submit(JobId { session: 1725, serial: 2, generation: 1 }, 1, scene, input); + assert_eq!(failed.err().unwrap().code, ErrorCode::LimitExceeded); + assert_eq!(host.admitted_bytes(), before); + assert!(host.0.shared.queue.lock().unwrap().is_empty()); + drop(fill); + assert_eq!(host.admitted_bytes(), 0); + } +} + +fn admit_request_sum(work_bytes: u64, request_bytes: u64) -> Result<()> { + if work_bytes.checked_add(request_bytes).is_none_or(|sum| sum > super::image::MAX_JOB_BYTES) { + return Err(JobError::new(ErrorCode::LimitExceeded, "render work and retained request exceed 384 MiB per-job admission")); + } + Ok(()) +} + +/// Borrow encoded bytes through the frame, so retaining the data also retains its admission lease. +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearColourEncoding { + SceneLinearSrgbD65, +} +#[derive(Clone, Copy, Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LinearAlphaConvention { + CoveragePremultiplied, +} +#[derive(Clone, Debug, Serialize)] +pub struct LinearMasterInfo { + pub encoding: LinearColourEncoding, + pub alpha: LinearAlphaConvention, + pub bytes: u64, + pub sha256: String, +} +struct RetainedPresentation { + info: super::presentation::MasterPresentation, + _reservation: Reservation, +} + +pub struct RenderFrame { + // Derivatives point directly at the original, never form a retention chain. + source_master: Option>, + presentation: Option>, + pub info: FrameInfo, + png: Vec, + exr: Option<(Vec, LinearMasterInfo)>, + _reservation: Reservation, +} +impl RenderFrame { + pub fn master_source(self: &Arc) -> Result> { + if let Some(source) = &self.source_master { + return Ok(source.clone()); + } + if self.exr.is_some() { + return Ok(self.clone()); + } + Err(JobError::new(ErrorCode::InvalidRequest, "completed image has no retained raw linear master")) + } + pub fn presentation(&self) -> Option<&super::presentation::MasterPresentation> { + self.presentation.as_deref().map(|retained| &retained.info) + } + pub fn linear_exr(&self) -> Option<&[u8]> { + self.exr.as_ref().map(|(bytes, _)| bytes.as_slice()).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_exr())) + } + pub fn linear_master_info(&self) -> Option<&LinearMasterInfo> { + self.exr.as_ref().map(|(_, info)| info).or_else(|| self.source_master.as_ref().and_then(|source| source.linear_master_info())) + } + pub fn png(&self) -> &[u8] { + &self.png + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct PreviewInfo { + pub frame_sequence: u32, + pub samples_per_pixel: u32, + pub frame: FrameInfo, +} + +/// Immutable checkpoint bytes retain their own transferred host lease. Keeping +/// an older preview alive never makes its memory disappear from pool accounting. +pub struct RenderPreview { + pub info: PreviewInfo, + png: Vec, + _reservation: CheckpointLease, +} + +/// Two reusable, immutable complete-pass slots. No consumer acknowledgement or +/// queue: externally pinned slots are diagnosed and never stall final work. +struct CheckpointCredits { + state: Mutex, + slot_bytes: u64, + capacity: u64, +} +struct CheckpointCreditState { + free: Reservation, + closed: bool, +} +impl CheckpointCredits { + fn new(reservation: &mut Reservation, slot_bytes: u64, slots: u32) -> Result> { + if !(1..=2).contains(&slots) || slot_bytes == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "checkpoint credits require one or two finite slots")); + } + let capacity = slot_bytes + .checked_mul(u64::from(slots)) + .and_then(|n| n.checked_add(1024)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit capacity overflow"))?; + let free = reservation.split(capacity)?; + Ok(Arc::new(Self { state: Mutex::new(CheckpointCreditState { free, closed: false }), slot_bytes, capacity })) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "checkpoint credit lock poisoned"))?; + if state.closed { + return Err(JobError::new(ErrorCode::Cancelled, "checkpoint credits are closed")); + } + let needed = self.slot_bytes.checked_add(1024).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint credit bound overflow"))?; + if state.free.bytes < needed { + return Ok(None); + } + let reservation = state.free.split(self.slot_bytes)?; + Ok(Some(CheckpointLease { reservation, credits: self.clone() })) + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + let _ = state.free.shrink(0); + } +} +struct CheckpointLease { + reservation: Reservation, + credits: Arc, +} +impl std::ops::Deref for CheckpointLease { + type Target = Reservation; + fn deref(&self) -> &Reservation { + &self.reservation + } +} +impl Drop for CheckpointLease { + fn drop(&mut self) { + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if !state.closed { + if state.free.bytes.checked_add(self.reservation.bytes).is_some_and(|n| n <= self.credits.capacity) + && state.free.merge_from(&mut self.reservation).is_ok() + { + return; + } + state.closed = true; + let _ = state.free.shrink(0); + } + } +} + +impl RenderPreview { + pub fn png(&self) -> &[u8] { + &self.png + } +} + +/// Metadata for either runtime environment contract; wire objects retain their original shape. +#[derive(Clone, Debug, Serialize)] +#[serde(untagged)] +pub enum JobEnvironmentInfo { + Cpu(crate::lighting::environment_input::EnvironmentInfo), + Gpu(crate::lighting::environment::EnvironmentInfo), +} + +#[derive(Clone, Debug, Serialize)] +pub struct JobStatus { + /// Completed CPU passes whose immutable snapshot could not be published + /// because both admitted slots remained pinned by external consumers. + pub cpu_preview_retention_skips: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub punctual_diagnostics: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub presentation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sampling: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub linear_master: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub preview: Option, + pub textures: Option, + pub options: JobOptions, + #[serde(skip_serializing_if = "Option::is_none")] + pub environment: Option, + pub job: JobId, + pub scene_generation: u64, + pub request: ImageRequest, + pub resolved: crate::ResolvedRequest, + pub progress: Progress, + pub error: Option, + pub frame: Option, +} + +struct Data { + cpu_preview_retention_skips: u32, + partial_preview: Option>, + punctual_diagnostics: Option, + sampling: Option, + progress: Progress, + error: Option, + frame: Option>, + preview: Option>, +} +struct Record { + partial: Option>, + presentation: Option>, + textures: Option, + options: JobOptions, + environment: Option, + id: JobId, + scene_generation: u64, + request: ImageRequest, + // Rust fields drop in declaration order: payload before its retained credits. + _request_reservation: Option, + resolved: crate::ResolvedRequest, + cancel: CancelToken, + data: Mutex, + #[cfg(not(target_arch = "wasm32"))] + done: Condvar, +} + +impl Record { + fn notify(&self) { + #[cfg(not(target_arch = "wasm32"))] + self.done.notify_all(); + } +} + +#[derive(Clone)] +pub struct JobHandle(Arc); + +impl JobHandle { + /// Internal admitted-work identity. Equal public IDs need not be one record. + pub(super) fn same_record(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + + pub fn id(&self) -> JobId { + self.0.id + } + pub fn status(&self) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + Ok(JobStatus { + cpu_preview_retention_skips: data.cpu_preview_retention_skips, + punctual_diagnostics: data.punctual_diagnostics, + presentation: self.0.presentation.as_deref().map(|retained| retained.info.clone()), + sampling: data.sampling.clone(), + linear_master: data.frame.as_ref().and_then(|frame| frame.linear_master_info().cloned()), + preview: data.preview.as_ref().map(|preview| preview.info.clone()), + textures: self.0.textures.clone(), + options: self.0.options, + environment: self.0.environment.clone(), + job: self.0.id, + scene_generation: self.0.scene_generation, + request: self.0.request.try_clone_for_host()?, + resolved: self.0.resolved.clone(), + progress: data.progress, + error: data.error.clone(), + frame: data.frame.as_ref().map(|f| f.info.clone()), + }) + } + pub fn cancel(&self) -> Result { + if let Some(credits) = &self.0.partial { + credits.close(); + } + let mut released_partial = None; + { + let mut data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + if !data.progress.phase.terminal() { + self.0.cancel.cancel(); + released_partial = data.partial_preview.take(); + data.preview = None; + data.progress.phase = if data.progress.phase == Phase::Queued { Phase::Cancelled } else { Phase::Cancelling }; + } + } + drop(released_partial); + self.0.notify(); + self.status() + } + + /// Native application helper; engine status commands remain non-blocking. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, timeout: std::time::Duration) -> Result { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + let (data, timed) = self + .0 + .done + .wait_timeout_while(data, timeout, |d| !d.progress.phase.terminal()) + .map_err(|_| JobError::new(ErrorCode::Internal, "render completion lock poisoned"))?; + if timed.timed_out() && !data.progress.phase.terminal() { + return Err(JobError::new(ErrorCode::TimedOut, "render wait timed out")); + } + drop(data); + self.status() + } + pub fn frame(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render result lock poisoned"))?; + let frame = data.frame.clone(); + if frame.as_ref().is_some_and(|f| f.info.job != self.0.id || f.info.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render frame identity does not match its job")); + } + Ok(frame) + } + + /// A provisional complete-pass image, never the final/export frame slot. + pub fn preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview lock poisoned"))?; + let preview = data.preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "render preview identity does not match its job")); + } + Ok(preview) + } +} + +#[derive(Clone, Copy)] +enum CpuPreviewPolicy { + Shared(super::PartialPreviewPlan), + Protected(super::ProtectedPreviewPlan), +} +impl CpuPreviewPolicy { + fn preview_plan(self) -> super::PartialPreviewPlan { + match self { + Self::Shared(plan) => plan, + Self::Protected(plan) => plan.preview_plan(), + } + } +} +struct Submission { + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, +} +struct Work { + regrade: Option<(Arc, super::presentation::Presentation)>, + request: Option, + executor: Option>, + environment: Option, + scene: ProductScene, + handle: JobHandle, + reservation: Reservation, +} +// One host advance hashes at most four 16 KiB chunks, independently of the +// integrator's quantum. The unchanged work reservation covers the sole PNG and +// this fixed state until publication; it is not another image task or pool. +const PNG_HASH_CHUNK_BYTES: usize = 16_384; +const PNG_HASH_CHUNKS_PER_ADVANCE: usize = 4; +pub(crate) const FRAME_METADATA_BYTES: u64 = 1024; + +struct PendingPng { + png: Vec, + digest: Sha256, + hashed: usize, + preview_samples: Option, + exr: Option>, + png_digest: Option>, + exr_hashed: usize, +} +// Keep the new fixed completion state within the existing metadata allowance +// even if the hashing dependency's representation changes on another target. +const _: [(); 1] = [(); (std::mem::size_of::() <= 512) as usize]; +const _: [(); 1] = [(); (std::mem::size_of::() + + std::mem::size_of::() + + std::mem::size_of::() + + 64 + + 2 * crate::MAX_RENDER_ID_BYTES + + 32 + <= FRAME_METADATA_BYTES as usize) as usize]; + +impl PendingPng { + fn new(png: Vec) -> Self { + Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, png_digest: None, exr_hashed: 0 } + } + + #[cfg(feature = "raytrace-cpu")] + fn preview(png: Vec, samples: u32) -> Self { + 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 { + cancel.check()?; + self.finish_png_digest(); + for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) { + 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) + } else { + break; + }; + let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len()); + 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())) + } + fn progress(&self) -> Progress { + Progress { + phase: Phase::Encoding, + done: self.hashed as u64 + self.exr_hashed as u64, + total: self.png.len() as u64 + self.exr.as_ref().map_or(0, |bytes| bytes.len() as u64), + } + } +} + +#[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 = (0..quantum_bytes + 13).map(|index| (index as u8).wrapping_mul(17).wrapping_add(3)).collect(); + let exr: Option> = 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>, + task: Option, + pending_png: Option, + handle: JobHandle, + reservation: Option, + next_preview_sequence: u32, + next_checkpoint_pass: u32, + checkpoints: Option>, + // Task/PNG allocations above die before the in-flight credit below. + partial: Option>, +} + +impl Drop for Running { + fn drop(&mut self) { + if let Some(credits) = &self.checkpoints { + credits.close(); + } + } +} + +/// One fallibly allocated task, keeping the dispatch enum small in either build. +/// Its bounded metadata allocation fits the existing per-job task allowance. +struct TaskSlot(Vec); +impl TaskSlot { + fn new(task: T) -> Result { + if std::mem::size_of::() > 4096 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task metadata exceeds its admission allowance")); + } + let mut tasks = Vec::new(); + tasks.try_reserve_exact(1).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve render task slot"))?; + if tasks.capacity() != 1 { + return Err(JobError::new(ErrorCode::LimitExceeded, "render task slot exceeds its bounded capacity")); + } + tasks.push(task); + Ok(Self(tasks)) + } + fn get_mut(&mut self) -> Result<&mut T> { + self.0.first_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task slot")) + } +} +enum WorkTask { + Regrade(TaskSlot), + Registered(Box), + Raster(TaskSlot), + #[cfg(feature = "raytrace-cpu")] + Raytrace(TaskSlot), +} + +enum WorkPoll { + #[cfg(feature = "raytrace-cpu")] + Partial { + png: Vec, + covered: Vec, + completed_passes: u32, + updated_prefix: u64, + }, + Existing(TaskPoll), + #[cfg(feature = "raytrace-cpu")] + Preview { + png: Vec, + samples_per_pixel: u32, + }, +} + +impl WorkTask { + fn protected_report(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.protected_preview_report()), + _ => None, + } + } + fn partial_ready(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => task.get_mut()?.partial_preview_ready(plan), + _ => Ok(false), + } + } + fn completed_pass_ready(&self, plan: super::PartialPreviewPlan) -> Result> { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().map_or(Ok(None), |task| task.completed_pass_preview_ready(plan)), + _ => Ok(None), + } + } + fn begin_partial(&mut self, plan: super::PartialPreviewPlan) -> Result { + let _ = &plan; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => match task.get_mut()?.begin_partial_preview(plan)? { + crate::raytrace::image::PartialBegin::Started => Ok(true), + crate::raytrace::image::PartialBegin::Exhausted => Ok(false), + }, + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn step_partial(&mut self, units: usize) -> Result { + let _ = &units; + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_partial_previews(units)? { + crate::raytrace::image::PartialImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::PartialImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::PartialImagePoll::Preview { png, covered, completed_passes, updated_prefix } => { + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } + } + }), + _ => Err(JobError::new(ErrorCode::InvalidRequest, "partial presentation requires the builtin CPU task")), + } + } + fn punctual_diagnostics(&self) -> Option { + match self { + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(slot) => slot.0.first().and_then(|task| task.punctual_diagnostics()), + _ => None, + } + } + + fn source_master(&self) -> Result>> { + match self { + Self::Regrade(slot) => { + slot.0.first().map(|task| Some(task.source())).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing master task slot")) + } + _ => Ok(None), + } + } + fn sampling_report(&self) -> Option { + match self { + Self::Registered(task) => task.sampling_report(), + _ => None, + } + } + fn take_linear_exr(&mut self) -> Option> { + match self { + Self::Registered(task) => task.take_linear_exr(), + _ => None, + } + } + fn new( + scene: ProductScene, + request: ImageRequest, + cancel: CancelToken, + environment: Option, + job_options: JobOptions, + partial: Option, + report_sink: Option<&PartialCredits>, + ) -> Result { + let _ = (&environment, &job_options, &partial, &report_sink); + match request.integrator { + Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster), + Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let options = request.raytrace.clone().unwrap_or_default(); + let task = match partial { + Some(CpuPreviewPolicy::Shared(plan)) => crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ), + Some(CpuPreviewPolicy::Protected(plan)) => { + crate::raytrace::image::ImageTask::new_with_environment_and_nested_and_protected_partial( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + plan, + ) + } + None => crate::raytrace::image::ImageTask::new_with_environment_and_nested( + scene, + request, + cancel, + options, + environment, + job_options.nested_media, + ), + }; + Self::raytrace_with_slot(task?, report_sink, TaskSlot::new) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + } + + fn step(&mut self, units: usize) -> Result { + match self { + Self::Regrade(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + Self::Registered(task) => task.step(units).map(WorkPoll::Existing), + Self::Raster(task) => task.get_mut()?.step(units).map(WorkPoll::Existing), + #[cfg(feature = "raytrace-cpu")] + Self::Raytrace(task) => Ok(match task.get_mut()?.step_with_previews(units)? { + crate::raytrace::image::ImagePoll::Pending(progress) => WorkPoll::Existing(TaskPoll::Pending(progress)), + crate::raytrace::image::ImagePoll::Complete(png) => WorkPoll::Existing(TaskPoll::Complete(png)), + crate::raytrace::image::ImagePoll::Preview { png, samples_per_pixel } => WorkPoll::Preview { png, samples_per_pixel }, + }), + } + } +} + +fn terminal(handle: &JobHandle, error: JobError) { + if let Some(credits) = &handle.0.partial { + credits.close(); + } + let mut released_partial = None; + if let Ok(mut data) = handle.0.data.lock() { + if data.progress.phase == Phase::Completed { + return; + } + if handle.0.cancel.is_cancelled() || error.code == ErrorCode::Cancelled { + data.progress.phase = Phase::Cancelled; + data.error = None; + } else { + data.progress.phase = Phase::Failed; + data.error = Some(error); + } + data.frame = None; + data.preview = None; + released_partial = data.partial_preview.take(); + } + drop(released_partial); + handle.0.notify(); +} + +impl Running { + fn begin(work: Work) -> Option { + Self::begin_with_partial_factory(work, |credits| TaskSlot::new(PartialRunning::new(credits))) + } + + // The private factory keeps post-construction setup fallible without losing + // the real ledger. It runs only after report capture and outside every lock. + fn begin_with_partial_factory( + mut work: Work, + make_partial: impl FnOnce(Arc) -> Result>, + ) -> Option { + let checkpoints = (|| { + let slots = work + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .filter(|_| work.handle.0.partial.is_none() && work.executor.is_none()) + .map_or(0, |options| options.samples_per_pixel.saturating_sub(1).min(2)); + if slots == 0 { + return Ok(None); + } + let slot_bytes = u64::from(work.handle.0.request.width) + .checked_mul(u64::from(work.handle.0.request.height)) + .and_then(|n| n.checked_mul(8)) + .and_then(|n| n.checked_add(65_536 + FRAME_METADATA_BYTES)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint slot overflow"))?; + CheckpointCredits::new(&mut work.reservation, slot_bytes, slots).map(Some) + })(); + let checkpoints = match checkpoints { + Ok(credits) => credits, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + if work.handle.0.cancel.is_cancelled() { + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render cancelled")); + return None; + } + if let Ok(mut data) = work.handle.0.data.lock() + && !work.handle.0.cancel.is_cancelled() + { + data.progress.phase = Phase::Preparing; + } + let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if let Some((source, presentation)) = work.regrade { + super::regrade::RegradeTask::new(source, presentation, work.handle.0.cancel.clone()).and_then(TaskSlot::new).map(WorkTask::Regrade) + } else if let Some(executor) = work.executor { + let request = work.request.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing registered executor request"))?; + executor.begin(work.scene, request, work.handle.0.options, work.handle.0.cancel.clone()).map(WorkTask::Registered) + } else { + WorkTask::new( + work.scene, + work.handle.0.request.try_clone_for_host()?, + work.handle.0.cancel.clone(), + work.environment, + work.handle.0.options, + work.handle.0.partial.as_ref().map(|credits| credits.policy()), + work.handle.0.partial.as_deref(), + ) + } + })) + .unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job"))); + let task = match task { + Ok(task) => task, + Err(error) => { + terminal(&work.handle, error); + return None; + } + }; + // The raw producer report was captured before the first task-slot wrap. + // Only now attempt the additional partial runtime slot. + let partial = work.handle.0.partial.as_ref().map(|credits| make_partial(credits.clone())).transpose(); + match partial { + Ok(partial) => Some(Self { + partial, + source_master: None, + task: Some(task), + pending_png: None, + handle: work.handle, + reservation: Some(work.reservation), + next_preview_sequence: 1, + next_checkpoint_pass: 1, + checkpoints, + }), + Err(error) => { + terminal(&work.handle, error); + // The real task's buffers die before work's remaining lease. + None + } + } + } + fn advance(&mut self, units: usize) -> Result { + self.handle.0.cancel.check()?; + if self.pending_png.is_some() { + return self.advance_png(units); + } + if let Some(partial) = self.partial.as_mut() { + let partial = partial.get_mut()?; + let task = self.task.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + let uniform_pass = task.completed_pass_ready(partial.credits.plan)?; + let automatic_pass = uniform_pass.filter(|pass| *pass > partial.last_pass_attempt); + if let Some(pass) = automatic_pass { + partial.last_pass_attempt = pass; + partial.credits.request()?; + } + if partial.lease.is_none() + && partial.credits.requested.load(Ordering::Acquire) + && !partial.credits.exhausted.load(Ordering::Acquire) + && (uniform_pass.is_none() || automatic_pass.is_some()) + { + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial CPU task"))?; + if task.partial_ready(partial.credits.plan)? { + let mut lease = partial.credits.acquire()?; + if lease.is_none() && automatic_pass.is_some() { + let released = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retirement lock poisoned"))? + .partial_preview + .take(); + drop(released); + lease = partial.credits.acquire()?; + } + if lease.is_none() && automatic_pass.is_some() && partial.credits.retained_slots_blocked()? { + let mut data = self + .handle + .0 + .data + .lock() + .map_err(|_| JobError::new(ErrorCode::Internal, "partial retention diagnostic lock poisoned"))?; + self.handle.0.cancel.check()?; + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial retention diagnostic overflow"))?; + } + if let Some(lease) = lease { + // Keep the lease past any producer error until task buffers drop. + partial.lease = Some(lease); + let begin = task.begin_partial(partial.credits.plan); + partial.credits.store_report(task.protected_report())?; + if !begin? { + if partial.credits.protected.is_some() && !partial.credits.exhausted.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::Internal, "protected feedback refused without real quota exhaustion")); + } + partial.credits.exhaust(); + drop(partial.lease.take()); + } + } + } + } + } + let task = self.task.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render task"))?; + let result = if self.partial.is_some() { task.step_partial(units) } else { task.step(units) }; + if let Some(credits) = &self.handle.0.partial { + credits.store_report(task.protected_report())?; + } + let result = result?; + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + data.punctual_diagnostics = self.task.as_ref().and_then(WorkTask::punctual_diagnostics); + // The final publication check is under the same lock as cancellation. + if self.handle.0.cancel.is_cancelled() { + data.progress.phase = Phase::Cancelled; + data.frame = None; + data.preview = None; + let released = data.partial_preview.take(); + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + return Ok(false); + } + match result { + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Partial { png, covered, completed_passes, updated_prefix } => { + drop(data); + self.capture_partial(png, covered, completed_passes, updated_prefix)?; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Pending(progress)) => { + data.progress = progress; + Ok(true) + } + WorkPoll::Existing(TaskPoll::Complete(png)) => { + // Drop every integrator-owned capture/scratch buffer first, but + // keep the original admission lease while hashing the sole PNG. + self.source_master = self.task.as_ref().map(WorkTask::source_master).transpose()?.flatten(); + data.sampling = self.task.as_ref().and_then(WorkTask::sampling_report); + let exr = self.task.as_mut().and_then(WorkTask::take_linear_exr); + if exr.is_some() != self.handle.0.options.linear_exr { + return Err(JobError::new(ErrorCode::Internal, "linear master availability differs from the admitted request")); + } + if let Some(bytes) = &exr { + let limit = super::linear_exr::encoded_limit(self.handle.0.request.width, self.handle.0.request.height)?; + if bytes.len() < 8 || bytes.capacity() as u64 > limit || bytes.get(..8) != Some(&[0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0]) { + return Err(JobError::new(ErrorCode::LimitExceeded, "linear master exceeds its bound or has an invalid signature")); + } + } + self.task = None; + let mut pending = PendingPng::new(png); + pending.exr = exr; + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + #[cfg(feature = "raytrace-cpu")] + WorkPoll::Preview { png, samples_per_pixel } => { + // Retain the integrator/film and the entire remaining work lease. + // Hash the checkpoint before making immutable bytes observable. + let pending = PendingPng::preview(png, samples_per_pixel); + data.progress = pending.progress(); + self.pending_png = Some(pending); + Ok(true) + } + } + } + + fn advance_png(&mut self, units: usize) -> Result { + // No status/data lock is held while scanning the encoded image. + let pending = self.pending_png.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing pending PNG"))?; + if !pending.step(units, &self.handle.0.cancel)? { + let progress = pending.progress(); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + self.handle.0.cancel.check()?; + data.progress = progress; + return Ok(true); + } + 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, png_digest); + } + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: self.handle.0.request.width, + height: self.handle.0.request.height, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + 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. + // The PNG allocation itself is retained once and billed by capacity below. + let frame_layout = if preview_samples.is_some() { std::mem::size_of::() } else { std::mem::size_of::() }; + let checkpoint_metadata = + if preview_samples.is_some() { std::mem::size_of::() + 2 * std::mem::size_of::() } else { 0 }; + let fixed_metadata = std::mem::size_of::() + frame_layout + checkpoint_metadata + 2 * crate::MAX_RENDER_ID_BYTES + 32; + let linear_digest_bytes = if exr.is_some() { 64 } else { 0 }; + if fixed_metadata + .checked_add(info.png_sha256.capacity()) + .and_then(|n| n.checked_add(linear_digest_bytes)) + .is_none_or(|bytes| bytes > FRAME_METADATA_BYTES as usize) + { + return Err(JobError::new(ErrorCode::LimitExceeded, "PNG digest metadata exceeds its existing admission allowance")); + } + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; + // Cancellation shares this lock; a late cancel must win before frame + // installation. The digest is complete; checkpoints retain task scratch, + // while the final-only path has already released it. + self.handle.0.cancel.check()?; + if let Some(samples_per_pixel) = preview_samples { + let options = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "preview requires CPU progressive intent"))?; + let frame_sequence = self.next_preview_sequence; + let expected = Some(self.next_checkpoint_pass); + if expected != Some(samples_per_pixel) || samples_per_pixel >= options.samples_per_pixel || self.task.is_none() { + return Err(JobError::new(ErrorCode::Internal, "invalid progressive checkpoint sequence")); + } + let next_sequence = frame_sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::Internal, "preview sequence exhausted"))?; + let credits = self.checkpoints.as_ref().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing checkpoint credits"))?; + if (png.capacity() as u64).checked_add(FRAME_METADATA_BYTES).is_none_or(|bytes| bytes > credits.slot_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "checkpoint PNG exceeds its admitted slot")); + } + let mut reservation = credits.acquire()?; + if reservation.is_none() { + // Retire the host's obsolete slot before treating a consumer as + // pinned. A headless client never has to acknowledge previews. + let released = data.preview.take(); + drop(data); + drop(released); + reservation = credits.acquire()?; + data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render preview publication lock poisoned"))?; + self.handle.0.cancel.check()?; + } + self.next_checkpoint_pass = self + .next_checkpoint_pass + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint pass ordinal exhausted"))?; + let Some(reservation) = reservation else { + data.cpu_preview_retention_skips = data + .cpu_preview_retention_skips + .checked_add(1) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "checkpoint retention diagnostic overflow"))?; + return Ok(true); + }; + data.preview = Some(Arc::new(RenderPreview { + info: PreviewInfo { frame_sequence, samples_per_pixel, frame: info }, + png, + _reservation: reservation, + })); + self.next_preview_sequence = next_sequence; + let pixels = u64::from(self.handle.0.request.width) * u64::from(self.handle.0.request.height); + data.progress = + Progress { phase: Phase::Running, done: pixels * u64::from(samples_per_pixel), total: pixels * u64::from(options.samples_per_pixel) }; + self.handle.0.notify(); + return Ok(true); + } + let exr = exr.map(|bytes| { + let info = LinearMasterInfo { + bytes: bytes.len() as u64, + sha256: format!("{:x}", digest.finalize()), + encoding: LinearColourEncoding::SceneLinearSrgbD65, + alpha: LinearAlphaConvention::CoveragePremultiplied, + }; + (bytes, info) + }); + let retained = png.capacity() as u64 + exr.as_ref().map_or(0, |(bytes, _)| bytes.capacity() as u64) + FRAME_METADATA_BYTES; + let mut reservation = self.reservation.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing render reservation"))?; + reservation.shrink(retained)?; + data.frame = Some(Arc::new(RenderFrame { + info, + png, + exr, + source_master: self.source_master.take(), + presentation: self.handle.0.presentation.clone(), + _reservation: reservation, + })); + data.preview = None; + let released = data.partial_preview.take(); + data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + if let Some(credits) = &self.checkpoints { + credits.close(); + } + drop(data); + if let Some(credits) = &self.handle.0.partial { + credits.close(); + } + drop(released); + self.handle.0.notify(); + Ok(false) + } + + fn guarded_step(&mut self, units: usize) -> bool { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.advance(units))); + match result { + Ok(Ok(more)) => more, + Ok(Err(e)) => { + terminal(&self.handle, e); + false + } + Err(_) => { + terminal(&self.handle, JobError::new(ErrorCode::Internal, "image host encountered an internal error")); + false + } + } + } +} + +struct Shared { + queue: Mutex>, + active: Mutex>>, + stop: AtomicBool, + budget: Arc, + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar, +} + +struct Owner { + executor: Option>, + shared: Arc, + kind: HostKind, + running: Mutex>, + #[cfg(not(target_arch = "wasm32"))] + _worker: Option>, +} + +impl Drop for Owner { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Release); + if let Ok(active) = self.shared.active.lock() + && let Some(record) = active.as_ref().and_then(Weak::upgrade) + { + let _ = JobHandle(record).cancel(); + } + if let Ok(mut queue) = self.shared.queue.lock() { + for work in queue.iter() { + let _ = work.handle.cancel(); + } + queue.clear(); + } + if let Ok(mut running) = self.running.lock() + && let Some(work) = running.take() + { + let _ = work.handle.cancel(); + terminal(&work.handle, JobError::new(ErrorCode::Cancelled, "render host closed")); + } + #[cfg(not(target_arch = "wasm32"))] + self.shared.wake.notify_all(); + // Detaching cannot stall the UI; the bounded worker observes stop/cancel at its next unit. + } +} + +#[derive(Clone)] +pub struct ImageHost(Arc); + +/// Builtin CPU constructors share the registered image host lifetime machinery. +pub type CpuHost = ImageHost; + +impl ImageHost { + fn shared(limit: u64) -> Arc { + Arc::new(Shared { + queue: Mutex::new(VecDeque::new()), + active: Mutex::new(None), + stop: AtomicBool::new(false), + budget: Arc::new(Budget { used: AtomicU64::new(0), limit }), + #[cfg(not(target_arch = "wasm32"))] + wake: Condvar::new(), + }) + } + + pub fn cooperative() -> Self { + Self(Arc::new(Owner { + executor: None, + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + /// A cooperative host over `executor` (pumped by its caller). + #[cfg(test)] + fn cooperative_with(executor: Arc) -> Self { + Self(Arc::new(Owner { + executor: Some(executor), + shared: Self::shared(MEMORY_LIMIT), + kind: HostKind::Cooperative, + running: Mutex::new(None), + #[cfg(not(target_arch = "wasm32"))] + _worker: None, + })) + } + + pub fn for_platform() -> Result { + #[cfg(target_arch = "wasm32")] + { + Ok(Self::cooperative()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let pool = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + let shared = Self::shared(pool); + let worker_shared = shared.clone(); + let worker = std::thread::Builder::new() + .name("solidcraft-render".into()) + .spawn(move || native_worker(worker_shared)) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, format!("could not start CPU image worker: {e}")))?; + Ok(Self(Arc::new(Owner { executor: None, shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + } + + /// Start an isolated bounded native worker. GPU discovery occurs before registration. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_executor(executor: Arc) -> Result { + let descriptor = executor.descriptor()?; + if descriptor.profiles.len() != 1 + || descriptor + .profiles + .iter() + .any(|p| p.mode != RenderMode::Preview || p.operation != RenderOperation::Image || p.formats != [RenderFormat::Png]) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "image worker currently accepts one Preview/Image/PNG profile")); + } + let limit = executor.memory_limit_bytes(); + let ceiling = if usize::BITS >= 64 { super::NATIVE_CPU_POOL_BYTES } else { MEMORY_LIMIT }; + if limit == 0 || limit > ceiling { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image pool exceeds supported address space")); + } + let shared = Self::shared(limit); + let worker_shared = shared.clone(); + let worker = std::thread::Builder::new() + .name("solidcraft-render".into()) + .spawn(move || native_worker(worker_shared)) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, format!("could not start image worker: {e}")))?; + Ok(Self(Arc::new(Owner { executor: Some(executor), shared, kind: HostKind::NativeWorker, running: Mutex::new(None), _worker: Some(worker) }))) + } + + pub fn kind(&self) -> HostKind { + self.0.kind + } + + pub fn same_host(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub fn is_available(&self) -> bool { + !self.0.shared.stop.load(Ordering::Acquire) + } + pub fn admitted_bytes(&self) -> u64 { + self.0.shared.budget.used.load(Ordering::Acquire) + } + + /// Internal completed-film adapter: the existing host budget, no new pool. + pub(crate) fn reserve_film_snapshot(&self, bytes: u64) -> Result { + if self.0.executor.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU film snapshots require the builtin CPU host")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU image host has stopped")); + } + if bytes > super::image::MAX_JOB_BYTES { + return Err(JobError::new(ErrorCode::LimitExceeded, "film snapshot exceeds per-job admission")); + } + self.0.shared.budget.reserve(bytes) + } + + pub fn descriptor(&self) -> Result { + self.descriptor_for(Integrator::Raster) + } + + pub fn job_limit_bytes(&self) -> u64 { + if self.0.executor.is_some() { self.0.shared.budget.limit } else { super::image::MAX_JOB_BYTES } + } + + pub fn pool_limit_bytes(&self) -> u64 { + self.0.shared.budget.limit + } + + pub fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { + self.admit_with_policy(scene, request, options, None) + } + /// Same canonical policy and complete retained/HDR accounting as protected submit. + /// Non-reserving estimate: submission still admits against the live pool. + pub fn admit_cpu_protected_partial_with_environment_and_options( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result { + self.validate_submission_environment(scene, request, environment)?; + let policy = Self::protected_preview_policy(request)?; + let (mut admission, request_bytes) = self.admit_submission(scene, request, options, environment, Some(policy))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(request_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "retained request admission overflow"))?; + Ok(admission) + } + + fn protected_preview_policy(request: &ImageRequest) -> Result { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require CPU progressive intent"))? + .samples_per_pixel; + let plan = super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())?; + Ok(CpuPreviewPolicy::Protected(plan)) + } + + fn validate_submission_environment( + &self, + scene: &ProductScene, + request: &ImageRequest, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + ) -> Result<()> { + if self.0.executor.is_some() && environment.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU environments")); + } + if environment.is_some() && request.integrator != Integrator::Raytrace { + return Err(JobError::new(ErrorCode::InvalidRequest, "environment lighting requires CPU raytrace")); + } + self.validate_integrator(request.integrator)?; + if environment.is_some() { + request.raytrace.as_ref().unwrap_or(&super::RaytraceOptions::default()).validate_environment_reflections(scene)?; + } + Ok(()) + } + + fn admit_submission( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + environment: Option<&crate::lighting::environment_input::EnvironmentInput>, + partial: Option, + ) -> Result<(Admission, u64)> { + if environment.is_some() && request.raytrace.as_ref().is_some_and(|options| options.directional_shadow_transmission) { + return Err(JobError::new(ErrorCode::InvalidRequest, "directional shadow transmission does not support HDR environments")); + } + let metadata_bytes = + (if environment.is_some() { std::mem::size_of::() as u64 } else { 0 }) + + request.retained_resource_metadata_bytes(); + let request_bytes = retained_request_bytes(request)? + .checked_add(metadata_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment metadata overflow"))?; + let mut admission = self.admit_with_policy(scene, request, options, partial)?; + let environment_bytes = + environment.map_or(Ok(0), |value| value.required_bytes()).map_err(|error| JobError::new(ErrorCode::InvalidRequest, error.to_string()))?; + admission.estimated_total_bytes = admission + .estimated_total_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + admission.preparation_bytes = admission + .preparation_bytes + .checked_add(environment_bytes) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "environment admission overflow"))?; + self.check_request_sum(admission.estimated_total_bytes, request_bytes, request.cpu_budget())?; + Ok((admission, request_bytes)) + } + + fn admit_with_policy( + &self, + scene: &ProductScene, + request: &ImageRequest, + options: JobOptions, + partial: Option, + ) -> Result { + request.validate_raster_request()?; + if self.0.executor.is_some() && (request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0) { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept Raster-only lights or exposure")); + } + if let Some(policy) = partial { + let plan = policy.preview_plan(); + if self.0.executor.is_some() + || request.integrator != Integrator::Raytrace + || request.transparent_background + || request.environment.is_some() + || request.textures.is_some() + || request.raytrace.as_ref().and_then(|v| v.progressive).is_none() + || plan != super::PartialPreviewPlan::new(request.width, request.height)? + { + return Err(JobError::new(ErrorCode::InvalidRequest, "partial previews require the canonical builtin CPU progressive request")); + } + if let CpuPreviewPolicy::Protected(protected) = policy { + let samples = request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "protected previews require a progressive sample target"))? + .samples_per_pixel; + protected.validate()?; + if protected != super::ProtectedPreviewPlan::new(request.width, request.height, samples, request.cpu_budget())? { + return Err(JobError::new(ErrorCode::InvalidRequest, "protected feedback plan does not match its admitted request")); + } + } + } + let scatter = |t: Option| t.and_then(|v| v.subsurface()).is_some_and(|s| s.active()); + if scene.meshes.iter().any(|b| scatter(b.transmission) || b.faces.iter().any(|f| scatter(f.transmission))) + && !self.0.executor.as_ref().is_some_and(|executor| executor.supports_subsurface()) + { + return Err(JobError::new(ErrorCode::InvalidRequest, "installed image producer does not implement interior subsurface random walks")); + } + + self.validate_integrator(request.integrator)?; + options.validate()?; + if let Some(executor) = &self.0.executor { + if request.raytrace.is_some() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept CPU raytrace options")); + } + if options.aging.active() && !executor.supports_aging() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot evaluate ordered surface aging")); + } + if options.finishing.photographic.active() && !executor.supports_photographic() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply photographic lens effects")); + } + if options.nested_media && !executor.supports_nested_media() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement certified nested media")); + } + if options.volume.is_some() && !executor.supports_volume() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement bounded homogeneous volume transport")); + } + if options.adaptive.is_some() && !executor.supports_adaptive_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement independent-pilot adaptive sampling")); + } + if options.transmission_samples != 1 && !executor.supports_transmission_sampling() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement transmission strata")); + } + if options.linear_exr && !executor.supports_linear_exr() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot retain a raw linear EXR")); + } + if options.finishing.bloom.is_some_and(|b| b.active()) && !executor.supports_bloom() { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement display bloom")); + } + if (!options.finishing.is_identity() || options.backdrop.is_some()) && !executor.supports_finishing() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this executor cannot apply the requested finishing/backdrop")); + } + let admission = executor.admit(scene, request, options)?; + if admission.estimated_total_bytes > self.job_limit_bytes() { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(admission) + } else { + request.cpu_budget().validate_execution()?; + // Only the existing nesting opt-in is admitted on the CPU raytrace path. + // Every other JobOptions field retains its exact default-only contract. + if (JobOptions { nested_media: false, ..options }) != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU images use raytrace options, not progressive sampling controls")); + } + if let Some(policy) = partial { + #[cfg(feature = "raytrace-cpu")] + { + let raytrace = request + .raytrace + .as_ref() + .ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "partial previews require CPU progressive options"))?; + return match policy { + CpuPreviewPolicy::Shared(plan) => { + crate::raytrace::image::admit_with_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + CpuPreviewPolicy::Protected(plan) => { + crate::raytrace::image::admit_with_protected_partial_preview(scene, request, raytrace, options.nested_media, plan) + } + }; + } + #[cfg(not(feature = "raytrace-cpu"))] + { + let _ = policy; + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + } + if !options.nested_media { + return admit(scene, request); + } + if request.integrator != Integrator::Raytrace || request.environment.is_some() || request.textures.is_some() || scene.has_transmission() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU nested media require explicit raytrace dielectric overrides")); + } + #[cfg(feature = "raytrace-cpu")] + { + let defaults = super::RaytraceOptions::default(); + let raytrace = request.raytrace.as_ref().unwrap_or(&defaults); + crate::raytrace::image::admit_with_nested(scene, request, raytrace, true) + } + #[cfg(not(feature = "raytrace-cpu"))] + { + Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) + } + } + } + + fn check_request_sum(&self, work: u64, request: u64, budget: super::CpuBudget) -> Result<()> { + if self.0.executor.is_none() { + if budget == super::CpuBudget::Compact { + return admit_request_sum(work, request); + } + if work.checked_add(request).is_none_or(|n| n > budget.limits().max_job_bytes) { + return Err(JobError::new(ErrorCode::LimitExceeded, "CPU work and retained request exceed the selected profile")); + } + return Ok(()); + } + if work.checked_add(request).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "registered image job exceeds its admitted host pool")); + } + Ok(()) + } + + /// Check the execution choice without capturing geometry or reserving memory. + pub fn validate_integrator(&self, integrator: Integrator) -> Result<()> { + if self.0.executor.is_some() && integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + if !self.is_available() { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing requires the native worker host")); + } + Ok(()) + } + + /// Select exactly one executor for this request. Never rely on registry order + /// to choose between raster and raytracing implementations. + pub fn descriptor_for(&self, integrator: Integrator) -> Result { + if let Some(executor) = &self.0.executor { + if integrator != Integrator::Raster { + return Err(JobError::new(ErrorCode::InvalidRequest, "registered image executors do not accept CPU raytrace requests")); + } + let mut descriptor = executor.descriptor()?; + if !self.is_available() { + descriptor.availability = Availability::Unavailable { reason: "image host has stopped".into() }; + } + return Ok(descriptor); + } + if integrator == Integrator::Raytrace && !cfg!(feature = "raytrace-cpu") { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")); + } + Ok(ExecutorDescriptor { + id: ExecutorId::new(match integrator { + Integrator::Raster => "cpu-product", + Integrator::Raytrace => "cpu-raytrace", + }) + .map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: if self.0.shared.stop.load(Ordering::Acquire) { + Availability::Unavailable { reason: "image host has stopped".into() } + } else if integrator == Integrator::Raytrace && self.kind() != HostKind::NativeWorker { + Availability::Unavailable { reason: "CPU raytracing requires the native worker host".into() } + } else { + Availability::Available + }, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: if integrator == Integrator::Raytrace && cfg!(feature = "raytrace-cpu") && self.kind() == HostKind::NativeWorker { + // Refraction is the certified thin-sheet/axis-aligned-box CPU preview + // contract. Admission still refuses unsupported geometry and combinations. + vec![crate::RenderFeature::Pbr, crate::RenderFeature::Hdri, crate::RenderFeature::Refraction] + } else { + vec![crate::RenderFeature::Pbr] + }, + }], + limits: if integrator == Integrator::Raytrace && self.kind() == HostKind::NativeWorker && usize::BITS >= 64 { + super::CpuBudget::Workstation.image_limits(false) + } else { + RenderLimits::default() + }, + scratch: ScratchLayout { sample_scale: 2, sample_bytes_per_pixel: 8, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }) + } + + /// Resolve a CPU request against its explicit envelope, never the largest advertised one. + pub fn descriptor_for_request(&self, request: &ImageRequest) -> Result { + let mut descriptor = self.descriptor_for(request.integrator)?; + if self.0.executor.is_none() && request.integrator == Integrator::Raytrace { + let budget = request.cpu_budget(); + budget.validate_execution()?; + budget.validate_image(request.width, request.height, request.raytrace.as_ref().and_then(|o| o.progressive))?; + descriptor.limits = budget.image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())); + } + Ok(descriptor) + } + + pub fn submit(&self, id: JobId, scene_generation: u64, scene: ProductScene, request: ImageRequest) -> Result { + self.submit_with_environment(id, scene_generation, scene, request, None) + } + + /// Captured HDR ownership stays in work, never serialized/cloned into status. + pub fn submit_with_environment( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + environment: Option, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, JobOptions::default(), environment) + } + + pub fn submit_with_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + ) -> Result { + self.submit_with_environment_and_options(id, scene_generation, scene, request, options, None) + } + + pub fn submit_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, None) + } + /// Transient CPU presentation policy. Final request and legacy observers are unchanged. + pub fn submit_cpu_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let plan = super::PartialPreviewPlan::new(request.width, request.height)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(CpuPreviewPolicy::Shared(plan))) + } + /// Opt-in protected feedback preserves ordinary work while admitting a finite extra quota. + pub fn submit_cpu_protected_partial_with_environment_and_options( + &self, + id: JobId, + scene_generation: u64, + scene: ProductScene, + request: ImageRequest, + options: JobOptions, + environment: Option, + ) -> Result { + let policy = Self::protected_preview_policy(&request)?; + self.submit_with_policy(Submission { id, scene_generation, scene, request, options, environment }, Some(policy)) + } + fn submit_with_policy(&self, input: Submission, partial_plan: Option) -> Result { + let Submission { id, scene_generation, scene, request, options, environment } = input; + self.validate_submission_environment(&scene, &request, environment.as_ref())?; + if id.session == 0 || id.serial == 0 || id.generation == 0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid render job identity")); + } + let environment_info = environment + .as_ref() + .map(|e| JobEnvironmentInfo::Cpu(e.metadata())) + .or_else(|| request.environment.as_ref().map(|source| JobEnvironmentInfo::Gpu(source.info().clone()))); + let textures = request.textures.as_ref().map(|source| source.summary()); + let mut features = scene.required_features(); + if environment.is_some() || request.environment.is_some() { + features.push(crate::RenderFeature::Hdri); + } + if request.integrator == Integrator::Raytrace + && request.raytrace.as_ref().is_some_and(|options| !options.dielectrics.is_empty()) + && !features.contains(&crate::RenderFeature::Refraction) + { + features.push(crate::RenderFeature::Refraction); + } + let (Admission { estimated_total_bytes, .. }, request_bytes) = + self.admit_submission(&scene, &request, options, environment.as_ref(), partial_plan)?; + let mut backend = crate::builtin_backend(); + let descriptor = self.descriptor_for_request(&request)?; + let expected_executor = descriptor.id.clone(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(request.width), + height: u64::from(request.height), + format: Some(RenderFormat::Png), + features, + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::HostUnavailable, e.to_string()))?; + if resolved.executor != expected_executor { + return Err(JobError::new(ErrorCode::HostUnavailable, "CPU product executor is unavailable")); + } + let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; + if self.0.shared.stop.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + self.check_request_sum(estimated_total_bytes, request_bytes, request.cpu_budget())?; + let mut reservation = self.0.shared.budget.reserve(estimated_total_bytes)?; + + let partial_credits = partial_plan + .map(|policy| match policy { + CpuPreviewPolicy::Shared(plan) => PartialCredits::new(plan, &mut reservation), + CpuPreviewPolicy::Protected(plan) => PartialCredits::new_protected(plan, &mut reservation), + }) + .transpose()?; + let request_reservation = if request_bytes == 0 { None } else { Some(self.0.shared.budget.reserve(request_bytes)?) }; + // Preserve the original CPU option capacities in the retained request and its lease. + // Registered executors instead move resource Arcs into work and keep a small public copy. + let (public_request, work_request) = if self.0.executor.is_some() { + (ImageRequest { environment: None, textures: None, ..request.clone() }, Some(request)) + } else { + (request, None) + }; + let handle = JobHandle(Arc::new(Record { + partial: partial_credits, + presentation: None, + textures, + options, + environment: environment_info, + _request_reservation: request_reservation, + id, + scene_generation, + request: public_request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: None, + request: work_request, + executor: self.0.executor.clone(), + scene, + handle: handle.clone(), + reservation, + environment, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Regrade the exact retained native master. No geometry, material, light or + /// device work is submitted. The original frame and its lease remain shared. + pub fn submit_regrade(&self, id: JobId, source: &JobHandle, presentation: super::presentation::Presentation) -> Result { + if id.session == 0 || id.serial == 0 || id.generation == 0 || id.session != source.id().session || id == source.id() { + return Err(JobError::new(ErrorCode::WrongOwner, "regrade requires a new identity in the source document session")); + } + let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; + let master = frame.master_source()?; + let bytes = super::regrade::required_bytes(&master, presentation)?; + let raw = master.linear_master_info().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "raw master metadata is missing"))?; + let origin = super::presentation::MasterPresentation { + source_job: source.id(), + master_job: master.info.job, + master_sha256: raw.sha256.clone(), + presentation, + denoise_applied: false, + }; + let metadata_bytes = (std::mem::size_of::() + origin.master_sha256.capacity() + 32) as u64; + if bytes.checked_add(metadata_bytes).is_none_or(|n| n > self.job_limit_bytes()) { + return Err(JobError::new(ErrorCode::LimitExceeded, "master presentation exceeds the installed host's resource budget")); + } + let limits = RenderLimits { max_scratch_bytes: self.job_limit_bytes(), ..super::GPU_PATH_LIMITS }; + let descriptor = ExecutorDescriptor { + id: ExecutorId::new("linear-master").map_err(|e| JobError::new(ErrorCode::Internal, e.to_string()))?, + availability: Availability::Available, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Image, + formats: vec![RenderFormat::Png], + features: Vec::new(), + }], + limits, + scratch: ScratchLayout { sample_scale: 1, sample_bytes_per_pixel: 32, output_bytes_per_pixel: 8, encoding_bytes_per_pixel: 8 }, + }; + let mut backend = crate::builtin_backend(); + backend.executors = vec![descriptor]; + let resolved = crate::resolve_request( + &[backend], + &crate::RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Image, + width: u64::from(frame.info.width), + height: u64::from(frame.info.height), + format: Some(RenderFormat::Png), + features: Vec::new(), + policy: Default::default(), + }, + ) + .map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?; + let request = ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + width: frame.info.width, + height: frame.info.height, + camera: source.0.request.camera, + background: presentation.background, + transparent_background: presentation.transparent_background, + environment: None, + textures: None, + integrator: Integrator::Raster, + raytrace: None, + }; + let options = JobOptions { + finishing: presentation.finishing, + backdrop: presentation.backdrop, + exposure_ev: presentation.exposure_ev, + tone_map: presentation.tone_map, + ..Default::default() + }; + let mut queue = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?; + if self.0.shared.stop.load(Ordering::Acquire) { + return Err(JobError::new(ErrorCode::HostUnavailable, "image host has stopped")); + } + queue.retain(|work| !work.handle.0.cancel.is_cancelled()); + if queue.len() >= QUEUE_LIMIT { + return Err(JobError::new(ErrorCode::QueueFull, "image queue is full")); + } + let reservation = self.0.shared.budget.reserve(bytes)?; + let metadata = self.0.shared.budget.reserve(metadata_bytes)?; + let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); + let handle = JobHandle(Arc::new(Record { + partial: None, + presentation: Some(origin), + textures: None, + options, + environment: None, + _request_reservation: None, + id, + scene_generation: frame.info.scene_generation, + request, + resolved, + cancel: CancelToken::default(), + data: Mutex::new(Data { + cpu_preview_retention_skips: 0, + partial_preview: None, + punctual_diagnostics: None, + sampling: None, + progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, + error: None, + frame: None, + preview: None, + }), + #[cfg(not(target_arch = "wasm32"))] + done: Condvar::new(), + })); + queue.push_back(Work { + regrade: Some((master, presentation)), + request: None, + executor: None, + environment: None, + scene: ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + handle: handle.clone(), + reservation, + }); + drop(queue); + #[cfg(not(target_arch = "wasm32"))] + self.0.shared.wake.notify_one(); + Ok(handle) + } + + /// Cooperative callers pump a small quantum independently of polling a job's status. + /// Native jobs run even when the UI is idle or a headless caller is not polling. + pub fn pump(&self, units: usize) -> Result { + if self.0.kind != HostKind::Cooperative { + return Ok(false); + } + let mut running = self.0.running.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "cooperative host lock poisoned"))?; + if running.is_none() { + let work = self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.pop_front(); + if let Some(work) = work { + *running = Running::begin(work); + } + } + if let Some(work) = running.as_mut() { + if let Ok(mut active) = self.0.shared.active.lock() { + *active = Some(Arc::downgrade(&work.handle.0)); + } + if !work.guarded_step(units) { + *running = None; + if let Ok(mut active) = self.0.shared.active.lock() { + *active = None; + } + } + } + Ok(running.is_some() + || !self.0.shared.queue.lock().map_err(|_| JobError::new(ErrorCode::HostUnavailable, "render queue lock poisoned"))?.is_empty()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn native_worker(shared: Arc) { + loop { + let mut queue = match shared.queue.lock() { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + while queue.is_empty() && !shared.stop.load(Ordering::Acquire) { + queue = match shared.wake.wait(queue) { + Ok(q) => q, + Err(_) => { + shared.stop.store(true, Ordering::Release); + return; + } + }; + } + if shared.stop.load(Ordering::Acquire) { + return; + } + let work = queue.pop_front(); + drop(queue); + let Some(mut running) = work.and_then(Running::begin) else { continue }; + if let Ok(mut active) = shared.active.lock() { + *active = Some(Arc::downgrade(&running.handle.0)); + } + loop { + if shared.stop.load(Ordering::Acquire) { + let _ = running.handle.cancel(); + } + if !running.guarded_step(4096) { + break; + } + } + if let Ok(mut active) = shared.active.lock() { + *active = None; + } + } +} +#[cfg(test)] +mod retained_request_tests { + use super::*; + #[test] + fn retained_emitters_bill_vector_and_original_name_capacities_in_same_pool() { + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("fixture"); + let mut emissions = Vec::with_capacity(32); + emissions.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Front, + }); + let options = request.raytrace.as_mut().unwrap(); + options.emissions = Some(emissions); + let expected = 8 * std::mem::size_of::() as u64 + + 32 * std::mem::size_of::() as u64 + + 256; + assert_eq!(retained_request_bytes(&request).unwrap(), expected); + let budget = Arc::new(Budget { used: AtomicU64::new(0), limit: MEMORY_LIMIT }); + let lease = budget.reserve(expected).unwrap(); + assert_eq!(budget.used.load(Ordering::Acquire), expected); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected, expected).is_ok()); + assert!(admit_request_sum(super::super::image::MAX_JOB_BYTES - expected + 1, expected).is_err()); + drop(lease); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn emitter_request_lease_survives_real_completion_frame_eviction_and_last_handle() { + let mut host = CpuHost::for_platform().unwrap(); + let mut request = request(); + let mut name = String::with_capacity(256); + name.push_str("emitter"); + let mut values = Vec::with_capacity(32); + values.push(super::super::SurfaceEmission { + body_index: 0, + body: name, + color: [1.0; 3], + strength: 1.0, + sides: super::super::EmissionSides::Both, + }); + request.raytrace.as_mut().unwrap().emissions = Some(values); + let expected = retained_request_bytes(&request).unwrap(); + let mesh = solidcraft_geom::Mesh { + positions: vec![solidcraft_geom::Vec3::ZERO, solidcraft_geom::Vec3::X, solidcraft_geom::Vec3::Y], + normals: vec![solidcraft_geom::Vec3::Z; 3], + triangles: vec![[0, 1, 2]], + tri_face: vec![0], + ..Default::default() + }; + let bounds = mesh.bounds(); + let scene = ProductScene { + meshes: vec![crate::ProductMesh { + transmission: None, + name: "emitter".into(), + mesh: Arc::new(mesh), + color: [255; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }], + bounds, + }; + let job = host.submit(JobId { session: 1695, serial: 1, generation: 1 }, 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + // Completion publication precedes the worker's last temporary handle release. + // Join this test's worker before asserting exact lease ownership, as in the union test. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let held = job.clone(); + job.0.data.lock().unwrap().frame = None; + drop(job); + assert!(host.admitted_bytes() > expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + assert_eq!(host.admitted_bytes(), 0); + } + fn request() -> ImageRequest { + let mut lights = Vec::with_capacity(8); + lights.push(super::super::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }); + 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: Integrator::Raytrace, + raytrace: Some(super::super::RaytraceOptions { lights: Some(lights), ..Default::default() }), + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + } + } + #[test] + fn retained_lights_are_billed_by_original_capacity_and_sum_is_checked() { + let request = request(); + let bytes = retained_request_bytes(&request).unwrap(); + assert_eq!(bytes, 8 * std::mem::size_of::() as u64); + let cap = super::super::image::MAX_JOB_BYTES; + assert!(admit_request_sum(cap - bytes, bytes).is_ok()); + assert_eq!(admit_request_sum(cap - bytes + 1, bytes).unwrap_err().code, ErrorCode::LimitExceeded); + assert_eq!(admit_request_sum(u64::MAX, 1).unwrap_err().code, ErrorCode::LimitExceeded); + } + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn retained_lights_keep_the_same_pool_lease_after_png_eviction() { + let host = CpuHost::for_platform().unwrap(); + let request = request(); + let expected = retained_request_bytes(&request).unwrap(); + let job = host + .submit( + JobId { session: 99, serial: 1, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + ) + .unwrap(); + assert_eq!(job.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); + let frame = job.frame().unwrap().unwrap(); + let held_bytes = host.admitted_bytes(); + assert!(held_bytes > expected); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), held_bytes); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), expected); + drop(held); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod environment_metadata_lease_tests { + use super::*; + #[test] + fn captured_environment_metadata_survives_png_eviction_without_source_bytes() { + use crate::lighting::{ + HdrSource, + environment_input::{EnvironmentInfo, 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]); + } + let input = EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.5, 2.0, 16).unwrap(); + let metadata = input.metadata(); + let expected = std::mem::size_of::() as u64; + let mut host = CpuHost::for_platform().unwrap(); + let budget = host.0.shared.budget.clone(); + let request = 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: Integrator::Raytrace, + raytrace: None, + camera: Default::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + }; + let job = host + .submit_with_environment( + JobId { session: 1693, serial: 7, generation: 1 }, + 1, + ProductScene { meshes: Vec::new(), bounds: solidcraft_geom::Aabb3::EMPTY }, + request, + Some(input), + ) + .unwrap(); + let status = job.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(matches!(status.environment, Some(JobEnvironmentInfo::Cpu(info)) if info.source_sha256 == metadata.source_sha256)); + host.join_worker_for_test().unwrap(); + let frame = job.frame().unwrap().unwrap(); + job.0.data.lock().unwrap().frame = None; + assert_eq!(host.admitted_bytes(), frame._reservation.bytes + expected); + drop(frame); + assert_eq!(host.admitted_bytes(), expected); + drop(host); + drop(job); + assert_eq!(budget.used.load(Ordering::Acquire), 0); + } +} + +#[cfg(all(test, feature = "raytrace-cpu", not(target_arch = "wasm32")))] +mod surface_request_metadata_tests { + use super::*; + use solidcraft_geom::{Aabb3, Mesh}; + #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] + #[test] + fn surface_request_lease_survives_completion_frame_eviction_and_held_handles() { + use crate::{ProductMesh, surface_patterns::SurfaceEffect}; + use std::time::{Duration, Instant}; + fn settle(host: &CpuHost, expected: u64) { + let deadline = Instant::now() + Duration::from_secs(10); + while host.admitted_bytes() != expected && Instant::now() < deadline { + std::thread::yield_now(); + } + assert_eq!(host.admitted_bytes(), expected); + } + let mut host = CpuHost::for_platform().unwrap(); + let mut meshes = Vec::new(); + let mut effects = Vec::with_capacity(32); + for index in 0..32 { + let mut name = String::with_capacity(256); + name.push_str(&format!("{index:03}")); + name.push_str(&"x".repeat(253)); + assert_eq!(name.capacity(), 256); + meshes.push(ProductMesh { + transmission: None, + name: name.clone(), + mesh: Arc::new(Mesh::default()), + color: [100; 3], + opacity: 1.0, + surface: None, + faces: Vec::new(), + }); + effects.push(SurfaceEffect { + body: name, + frame: Default::default(), + repeat_mm: [20.0; 3], + roughness_amplitude: 0.0, + bump_amplitude_mm: 0.0, + }); + } + let scene = ProductScene { meshes, bounds: Aabb3 { min: solidcraft_geom::Vec3::ZERO, max: solidcraft_geom::Vec3::ZERO } }; + let mut request = request(); + request.integrator = Integrator::Raytrace; + request.raytrace = Some(super::super::RaytraceOptions { surface_effects: Some(effects), ..Default::default() }); + let metadata = retained_request_bytes(&request).unwrap(); + assert!(metadata >= 32 * 256); + let mut oversized = request.clone(); + let mut overallocated = Vec::with_capacity(64); + overallocated.extend(oversized.raytrace.as_mut().unwrap().surface_effects.take().unwrap()); + oversized.raytrace.as_mut().unwrap().surface_effects = Some(overallocated); + assert!(host.submit(id(40, 1), 1, scene.clone(), oversized).is_err()); + assert_eq!(host.admitted_bytes(), 0); + + let job = host.submit(id(40, 2), 1, scene, request).unwrap(); + assert_eq!(job.wait_timeout(Duration::from_secs(10)).unwrap().progress.phase, Phase::Completed); + // Wait for this host's last temporary worker handle before exact lease checks. + host.0.shared.stop.store(true, Ordering::Release); + host.0.shared.wake.notify_all(); + Arc::get_mut(&mut host.0).unwrap()._worker.take().unwrap().join().unwrap(); + let frame = job.frame().unwrap().unwrap(); + let png_bytes = frame._reservation.bytes; + settle(&host, metadata + png_bytes); + // Evict the record's frame under the same lock used by publication, while + // an external frame and a cloned job handle retain their independent leases. + job.0.data.lock().unwrap().frame = None; + let held = job.clone(); + drop(job); + assert_eq!(host.admitted_bytes(), metadata + png_bytes); + drop(frame); + settle(&host, metadata); + assert_eq!(held.status().unwrap().request.raytrace.unwrap().surface_effects.unwrap().len(), 32); + drop(held); + settle(&host, 0); + } + + fn request() -> ImageRequest { + 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: Default::default(), + raytrace: None, + camera: Default::default(), + width: 16, + height: 16, + background: [40, 80, 120], + transparent_background: false, + } + } + + fn id(owner: u64, serial: u64) -> JobId { + JobId { session: owner, serial, generation: serial } + } +} + +/// Provisional source-film observation, separate from complete-pass previews. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PartialPreviewProjection { + TopLeftRepresentativeV1, +} +#[derive(Clone, Debug, Serialize)] +pub struct PartialPreviewInfo { + pub frame: FrameInfo, + pub sequence: u64, + pub source_width: u32, + pub source_height: u32, + pub completed_passes: u32, + pub updated_prefix: u64, + pub projection: PartialPreviewProjection, +} +/// Fields drop in declaration order: payload allocations die before credit return. +pub struct RenderPartialPreview { + pub info: PartialPreviewInfo, + png: Vec, + covered: Vec, + _lease: ReturnReservation, +} +const _: [(); 1] = [(); (std::mem::size_of::() + 2 * crate::MAX_RENDER_ID_BYTES + 256 <= 2048) as usize]; +impl RenderPartialPreview { + pub fn png(&self) -> &[u8] { + &self.png + } + pub fn covered(&self) -> &[u32] { + &self.covered + } +} +struct PartialCreditState { + report: Option, + free: Reservation, + in_flight: bool, + closed: bool, +} +struct PartialCredits { + protected: Option, + plan: super::PartialPreviewPlan, + state: Mutex, + requested: AtomicBool, + exhausted: AtomicBool, + _metadata: Reservation, +} +const _: [(); 1] = + [(); (std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::>() + 128 + <= 1024) as usize]; +impl PartialCredits { + fn new(plan: super::PartialPreviewPlan, reservation: &mut Reservation) -> Result> { + Self::new_with_protection(plan, None, reservation) + } + fn new_protected(plan: super::ProtectedPreviewPlan, reservation: &mut Reservation) -> Result> { + plan.validate()?; + Self::new_with_protection(plan.preview_plan(), Some(plan), reservation) + } + fn new_with_protection( + plan: super::PartialPreviewPlan, + protected: Option, + reservation: &mut Reservation, + ) -> Result> { + plan.validate()?; + let metadata = reservation.split(1024)?; + let bytes = plan.slot_bytes()?.checked_mul(2).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial credit overflow"))?; + let free = reservation.split(bytes)?; + Ok(Arc::new(Self { + plan, + protected, + state: Mutex::new(PartialCreditState { report: None, free, in_flight: false, closed: false }), + requested: AtomicBool::new(false), + exhausted: AtomicBool::new(false), + _metadata: metadata, + })) + } + fn request(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || self.exhausted.load(Ordering::Acquire) { + return Ok(false); + } + self.requested.store(true, Ordering::Release); + Ok(true) + } + fn acquire(self: &Arc) -> Result> { + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + let bytes = self.plan.slot_bytes()?; + if state.closed + || state.in_flight + || self.exhausted.load(Ordering::Acquire) + || !self.requested.load(Ordering::Acquire) + || state.free.bytes < bytes + { + return Ok(None); + } + let reservation = state.free.split(bytes)?; + state.in_flight = true; + self.requested.store(false, Ordering::Release); + Ok(Some(ReturnReservation { reservation: Some(reservation), credits: self.clone(), in_flight: true })) + } + fn retained_slots_blocked(&self) -> Result { + let state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial retention lock poisoned"))?; + Ok(!state.closed + && !state.in_flight + && !self.exhausted.load(Ordering::Acquire) + && self.requested.load(Ordering::Acquire) + && state.free.bytes < self.plan.slot_bytes()?) + } + fn exhaust(&self) { + self.exhausted.store(true, Ordering::Release); + self.requested.store(false, Ordering::Release); + } + fn close(&self) { + let mut state = match self.state.lock() { + Ok(state) => state, + Err(error) => error.into_inner(), + }; + state.closed = true; + state.in_flight = false; + self.requested.store(false, Ordering::Release); + // Atomic release only: no image destruction or user work under this lock. + let _ = state.free.shrink(0); + } +} +/// Unique lease; Arc payload clones never create another independent slot. +struct ReturnReservation { + reservation: Option, + credits: Arc, + in_flight: bool, +} +impl ReturnReservation { + fn published(&mut self) -> Result<()> { + let mut state = self.credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "partial credit lock poisoned"))?; + if state.closed || !state.in_flight || !self.in_flight { + return Err(JobError::new(ErrorCode::Cancelled, "partial preview credit is no longer current")); + } + state.in_flight = false; + self.in_flight = false; + Ok(()) + } +} +impl Drop for ReturnReservation { + fn drop(&mut self) { + let Some(mut reservation) = self.reservation.take() else { return }; + let mut state = match self.credits.state.lock() { + Ok(state) => state, + Err(error) => { + let mut state = error.into_inner(); + state.closed = true; + let _ = state.free.shrink(0); + state + } + }; + if self.in_flight { + state.in_flight = false; + } + if !state.closed { + let limit = self.credits.plan.slot_bytes().ok().and_then(|v| v.checked_mul(2)); + if state.free.bytes.checked_add(reservation.bytes).zip(limit).is_some_and(|(total, limit)| total <= limit) { + if state.free.merge_from(&mut reservation).is_err() { + state.closed = true; + let _ = state.free.shrink(0); + } + } else { + state.closed = true; + let _ = state.free.shrink(0); + } + } + drop(state); + // A closed sink releases this uniquely held reservation globally. + } +} +struct PartialPending { + covered: Vec, + completed_passes: u32, + updated_prefix: u64, +} +// Error paths preserve the same payload-before-lease destruction order. +struct PartialPublication { + png: Vec, + pending: PartialPending, + lease: ReturnReservation, +} +struct PartialRunning { + last_pass_attempt: u32, + pending: Option, + lease: Option, + credits: Arc, + next_sequence: u64, +} +impl PartialRunning { + fn new(credits: Arc) -> Self { + Self { pending: None, lease: None, credits, next_sequence: 1, last_pass_attempt: 0 } + } +} +impl JobHandle { + /// Real producer usage, unavailable until a protected task was actually constructed. + pub fn protected_preview_report(&self) -> Result> { + self.0.partial.as_ref().map_or(Ok(None), |credits| { + let state = credits.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + Ok(state.report) + }) + } + /// Request presentation only; this is not a visual-authority certificate. + pub fn request_partial_preview(&self) -> Result { + let terminal = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?.progress.phase.terminal(); + if terminal { + return Ok(false); + } + self.0.partial.as_ref().map_or(Ok(false), |credits| credits.request()) + } + pub fn partial_preview_exhausted(&self) -> Result { + Ok(self.0.partial.as_ref().is_some_and(|credits| credits.exhausted.load(Ordering::Acquire))) + } + pub fn partial_preview(&self) -> Result>> { + let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial preview lock poisoned"))?; + let preview = data.partial_preview.clone(); + if preview.as_ref().is_some_and(|p| p.info.frame.job != self.0.id || p.info.frame.scene_generation != self.0.scene_generation) { + return Err(JobError::new(ErrorCode::WrongOwner, "partial preview identity does not match its job")); + } + Ok(preview) + } +} +impl Running { + #[cfg(feature = "raytrace-cpu")] + fn capture_partial(&mut self, png: Vec, covered: Vec, completed_passes: u32, updated_prefix: u64) -> Result<()> { + self.handle.0.cancel.check()?; + let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without its policy"))?.get_mut()?; + let plan = partial.credits.plan; + let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height()); + let target = self + .handle + .0 + .request + .raytrace + .as_ref() + .and_then(|v| v.progressive) + .ok_or_else(|| JobError::new(ErrorCode::Internal, "partial output without progressive intent"))? + .samples_per_pixel; + let covered_limit = plan.covered_bytes()?; + if partial.lease.is_none() + || partial.pending.is_some() + || completed_passes >= target + || updated_prefix >= source_pixels + || (completed_passes == 0 && updated_prefix == 0) + || covered.len() as u64 != plan.pixels() + || (covered.capacity() as u64).checked_mul(4).is_none_or(|v| v > covered_limit) + || png.capacity() as u64 > plan.encoded_limit()? + { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload exceeds its admitted frontier or capacities")); + } + // This sole sidecar verification scan was included in the producer's precharge. + for (index, count) in covered.iter().enumerate() { + self.handle.0.cancel.check()?; + let source = plan.source_index(index)? as u64; + let samples = completed_passes + .checked_add(u32::from(source < updated_prefix)) + .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial sample count overflow"))?; + if *count > samples { + return Err(JobError::new(ErrorCode::Internal, "partial coverage exceeds committed source samples")); + } + } + partial.pending = Some(PartialPending { covered, completed_passes, updated_prefix }); + self.pending_png = Some(PendingPng::new(png)); + Ok(()) + } + fn publish_partial(&mut self, png: Vec, digest: sha2::digest::Output) -> Result { + 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"))?; + let lease = partial.lease.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication credit"))?; + let mut publication = PartialPublication { png, pending, lease }; + let sequence = partial.next_sequence; + let next = sequence.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial preview sequence exhausted"))?; + let plan = partial.credits.plan; + let info = FrameInfo { + job: self.handle.0.id, + scene_generation: self.handle.0.scene_generation, + backend: self.handle.0.resolved.backend.clone(), + executor: self.handle.0.resolved.executor.clone(), + width: plan.width(), + height: plan.height(), + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: publication.png.len() as u64, + png_sha256: format!("{:x}", digest), + }; + let metadata = std::mem::size_of::() + .checked_add(64 + 2 * crate::MAX_RENDER_ID_BYTES) + .and_then(|v| v.checked_add(info.png_sha256.capacity())); + if metadata.is_none_or(|v| v > 2048) { + return Err(JobError::new(ErrorCode::LimitExceeded, "partial payload metadata exceeds its slot")); + } + // No Data lock while touching the credit coordinator. + publication.lease.published()?; + let PartialPublication { png, pending, lease } = publication; + let preview = Arc::new(RenderPartialPreview { + info: PartialPreviewInfo { + frame: info, + sequence, + source_width: plan.source_width(), + source_height: plan.source_height(), + completed_passes: pending.completed_passes, + updated_prefix: pending.updated_prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }, + png, + covered: pending.covered, + _lease: lease, + }); + let mut data = self.handle.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render partial publication lock poisoned"))?; + if self.handle.0.cancel.is_cancelled() || data.progress.phase.terminal() { + drop(data); + drop(preview); + return Err(JobError::new(ErrorCode::Cancelled, "late partial preview refused")); + } + let released = data.partial_preview.replace(preview); + partial.next_sequence = next; + // A demand arriving during encoding remains pending; never clear it here. + drop(data); + drop(released); + self.handle.0.notify(); + Ok(true) + } +} + +impl PartialCredits { + fn policy(&self) -> CpuPreviewPolicy { + self.protected.map_or(CpuPreviewPolicy::Shared(self.plan), CpuPreviewPolicy::Protected) + } + fn store_report(&self, report: Option) -> Result<()> { + let (plan, report) = match (self.protected, report) { + (None, None) => return Ok(()), + (Some(plan), Some(report)) => (plan, report), + _ => return Err(JobError::new(ErrorCode::Internal, "producer work report differs from its admitted policy")), + }; + let presentation = plan.presentation_limit()?; + let aggregate = plan.aggregate_limit()?; + let expected_v = plan.snapshot_work()?.checked_mul(u64::from(report.accepted_snapshots)); + let used = report.ordinary_used.checked_add(report.presentation_used); + if report.policy_version != 1 + || report.ordinary_limit != plan.ordinary_limit() + || report.presentation_limit != presentation + || report.aggregate_limit != aggregate + || report.quota_limit != plan.quota_limit() + || report.ordinary_used > report.ordinary_limit + || report.presentation_used > presentation + || used.is_none_or(|v| v > aggregate) + || expected_v != Some(report.presentation_used) + || report.accepted_snapshots > report.next_milestone_index + || report.next_milestone_index > report.quota_limit + || report.quota_exhausted != (report.accepted_snapshots == report.quota_limit) + || report.milestones_complete != (report.next_milestone_index == report.quota_limit) + { + return Err(JobError::new(ErrorCode::Internal, "protected work report violates its actual admission")); + } + let mut state = self.state.lock().map_err(|_| JobError::new(ErrorCode::Internal, "protected report lock poisoned"))?; + if state.report.is_some_and(|previous| { + previous.ordinary_used > report.ordinary_used + || previous.presentation_used > report.presentation_used + || previous.accepted_snapshots > report.accepted_snapshots + || previous.next_milestone_index > report.next_milestone_index + }) { + drop(state); + return Err(JobError::new(ErrorCode::Internal, "protected work report counters moved backwards")); + } + state.report = Some(report); + if report.quota_exhausted { + self.exhaust(); + } + Ok(()) + } +} + +impl WorkTask { + #[cfg(feature = "raytrace-cpu")] + fn raytrace_with_slot( + task: crate::raytrace::image::ImageTask, + report_sink: Option<&PartialCredits>, + make_slot: impl FnOnce(crate::raytrace::image::ImageTask) -> Result>, + ) -> Result { + // ImageTask is already real, even if its host wrapper cannot be allocated. + if let Some(credits) = report_sink { + credits.store_report(task.protected_preview_report())?; + } + make_slot(task).map(Self::Raytrace) + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/delta-LF-review.patch b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/delta-LF-review.patch new file mode 100644 index 000000000..963a5d8f8 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/delta-LF-review.patch @@ -0,0 +1,10 @@ +--- a/crates/render/src/job/host.rs ++++ b/crates/render/src/job/host.rs +@@ -842,7 +842,6 @@ + } + } + } +- + + struct Running { + source_master: Option>, diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/source-bindings.json b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/source-bindings.json new file mode 100644 index 000000000..1d3f4b2f2 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/current-c28-host/source-bindings.json @@ -0,0 +1,27 @@ +{ + "status": "EXACT_C28_COMPILED_HOST_REFERENCE_NOT_COMPATIBILITY_WIP", + "base_source_manifest_sha256": "d38a8d946b6653864ad8918d4da662725bd24ca01b2e5aa2d3b38b47b1a7e163", + "source_binding": "RAW before of the sealed compatibility owner packet, preserved as the exact earlier C28 formatted source; not the compatibility candidate.", + "files": [ + { + "path": "crates/render/src/job/host.rs", + "before_sha256": "2c72c307ec49a94b100f4be32ab6a4af4be494199ff7ad5c87bb698e7f13ab4e", + "before_bytes": 135425, + "after_sha256": "9dbf55511147641a8d7d7c3b4bf444ae8b8ece154aab49db4b57cb208347b4a8", + "after_bytes": 135424 + } + ], + "delta": "Exactly one LF removed by the earlier C28 formatter, no other bytes changed from the SHA-state recovery.", + "known_C28_result": { + "build": "five library artifacts; ten inventories completed", + "selected_cases": 983, + "passed": 28, + "failed_font_fixture": 1, + "unrun": 954, + "cpu_supported_true_markers": 2, + "postchecks_executed": false, + "native_acceptance": false, + "full_CI_or_readiness": false + }, + "standalone_full_source_or_new_execution_claim": false +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/README.md b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/README.md new file mode 100644 index 000000000..a0ad734bd --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/README.md @@ -0,0 +1,17 @@ +# Case 976 isolated font-fixture correction + +One RAW candidate adds only crate::fonts::setup_bundled_fonts(&ctx) after the +new test's separate Context::default(), before it paints the existing UI kit. +Removing that line recovers the entire captured before file byte for byte. +All assertions, pass targets, seed and mode values are unchanged. + +The sealed C28 failure was an unbound ui-semibold font in this separate test +context. Actual app and Harness already register the bundled fonts. This is not +a demonstrated product cap/transport defect, nor an SPP assertion result. +The correction itself is **UNRUN**; its target test must be executed again on an +authorized exact composition. No product font default or new framework changes. + +**Do not overlay this full candidate onto ui.** Both test-file candidates start +from the same before 28ddafe4. This file lacks ui's five new tests and four neutral +constructor insertions. Preserve the one-line correction during later exact +delta composition; there is no precomposed source in this archive. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/candidate/crates/ui-egui/src/render_workspace_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/candidate/crates/ui-egui/src/render_workspace_tests.rs new file mode 100644 index 000000000..4fc7a55ac --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/candidate/crates/ui-egui/src/render_workspace_tests.rs @@ -0,0 +1,11591 @@ +use super::*; +use crate::scenario::Harness; +use solidcraft_engine::Session; + +fn environment_editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 1800.0))), events, ..Default::default() }, + |ui| { + ui.set_width(308.0); + environment::editor(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +fn environment_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"gpu_path","options":{"environment":{"kind":"sky"}}}}})).unwrap(); + setups::load(&mut h.app); + h +} + +#[test] +fn environment_editor_e4_variants_keep_all_five_sections_in_order() { + for variant in ["embedded", "sky", "file"] { + let mut h = environment_editor_fixture(); + if variant == "embedded" { + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + } else if variant == "file" { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "C:/hdr/studio.hdr".into() }; + } else { + h.app.render_workspace.view.studio.backdrop_enabled = true; + } + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let mut previous = -1.0; + let source_row = crate::scenario::rect_of("dialog:control:Source").unwrap(); + let change = crate::scenario::rect_of("render:environment:change").unwrap(); + assert!(source_row.contains_rect(change), "{variant}: Change must fit beside Source"); + for key in [ + "render.env_source", + "render.environment.orientation", + "render.env_backdrop", + "render.environment.ground", + "render.environment.atmosphere", + ] { + let rect = crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap(); + assert!(rect.top() > previous, "{variant}: {key} out of order"); + previous = rect.top(); + } + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.replace", + "render.environment.fit", + "render.environment.floor_wall", + "render.environment.cyclorama", + "render.environment.medium", + "render.environment.phase", + ] { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}: {text}"); + } + for key in match variant { + "embedded" => &["render.environment.embedded", "render.environment.builtin"][..], + "file" => &["render.environment.choose", "render.environment.check"][..], + _ => &[ + "render.environment.zenith", + "render.environment.horizon", + "render.environment.sky_ground", + "render.environment.start", + "render.environment.end", + ][..], + } { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}"); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "opening {variant} must never save"); + output.textures_delta.clear(); + } +} + +#[test] +fn environment_editor_unsupported_methods_keep_controls_and_reasons_without_switching() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = environment_editor_fixture(); + h.app.render_workspace.view.method = method; + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.needs_gpu", + "render.environment.gradient_gpu", + "render.environment.blur_pending", + "render.environment.world_pending", + "render.environment.medium", + "render.environment.min", + "render.environment.max", + ] { + assert!(text.contains(h.app.tr(key)), "missing {key}: {text}"); + } + output.textures_delta.clear(); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_none()); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn environment_editor_gradient_and_atmosphere_refuse_hostile_values_atomically() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for value in [f64::NAN, f64::INFINITY, -1.0, 1e300] { + let mut gradient = h.app.render_workspace.view.studio.backdrop; + gradient.radius = value; + assert!(environment::commit_gradient(&mut h.app, true, gradient).is_err()); + h.app.render_workspace.view.studio.volume = + Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: value, ..Default::default() }); + assert!(setups::save(&mut h.app).is_err()); + h.app.render_workspace.view.studio.volume = None; + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + environment::commit_gradient(&mut h.app, true, Default::default()).unwrap(); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_editor_stage_removal_requires_confirm_and_rejects_stale_answers() { + for stale in [false, true] { + let mut h = environment_editor_fixture(); + environment::commit_ground(&mut h.app, true, environment::Ground { margin: 1.0, gap: 0.1, color: [0.18; 3] }).unwrap(); + let before = h.app.session.doc.clone(); + environment::request_stage_removal(&h.app, &h.ctx); + for _ in 0..3 { + environment_editor_frame(&mut h, vec![]); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(crate::scenario::rect_of("dialog:ok").is_some()); + if stale { + h.app.run("render.settings.set", json!({"name":"Other","set":{"width":42}})).unwrap(); + } + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("dialog:ok").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert_eq!(h.app.session.undo.len(), undo + usize::from(!stale)); + assert_eq!(h.app.render_workspace.view.draft.stage.is_empty(), !stale); + } +} + +#[test] +fn environment_editor_checked_file_embeds_bytes_and_keeps_the_recheck_banner() { + let mut h = environment_editor_fixture(); + let path = h.dir.join("environment-editor.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + environment::persist(&mut h.app); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + assert!(matches!(h.app.render_workspace.view.studio.hdr, hdr::Input::FileCaptured { .. })); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.job.text.contains(h.app.tr("render.environment.checked")))); + output.textures_delta.clear(); + let before = h.app.session.doc.clone(); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + environment::persist(&mut h.app); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "changed bytes require rechecking"); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_medium_toggle_saves_one_command_without_a_gpu_host() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + let undo = h.app.session.undo.len(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_some()); + assert_eq!(h.app.session.undo.len(), undo + 1); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(h.app.session.doc.render.setups[&h.app.render_workspace.view.name], expected); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.studio.volume.is_none()); +} + +#[test] +fn environment_ring_angles_snap_wrap_and_refuse_hostile_geometry() { + let center = egui::pos2(100.0, 200.0); + for (point, expected) in + [(egui::pos2(150.0, 200.0), 0.0), (egui::pos2(100.0, 250.0), 90.0), (egui::pos2(50.0, 200.0), 180.0), (egui::pos2(100.0, 150.0), -90.0)] + { + assert_eq!(environment::pointer_angle(point, center, 50.0), Some(expected)); + } + assert_eq!(environment::drag_rotation(170.0, 170.0, -170.0, false), Some(-170.0)); + assert_eq!(environment::drag_rotation(170.0, 0.0, 30.0, true), Some(-165.0)); + assert_eq!(environment::drag_rotation(-170.0, 0.0, -30.0, true), Some(165.0)); + assert_eq!(environment::drag_rotation(0.0, 0.0, 180.0, false), Some(-180.0)); + assert_eq!(environment::pointer_angle(center, center, 50.0), None); + for radius in [0.0, -1.0, f32::NAN, f32::INFINITY, 1e9] { + assert_eq!(environment::pointer_angle(egui::pos2(150.0, 200.0), center, radius), None); + } + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(environment::pointer_angle(egui::pos2(value, 200.0), center, 50.0), None); + assert_eq!(environment::pointer_angle(center, egui::pos2(100.0, value), 50.0), None); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300] { + assert_eq!(environment::drag_rotation(value, 0.0, 20.0, false), None); + assert_eq!(environment::drag_rotation(0.0, value, 20.0, true), None); + assert_eq!(environment::drag_rotation(0.0, 0.0, value, false), None); + } +} + +fn environment_ring_frame(h: &mut Harness, mods: egui::Modifiers, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + focused: true, + events: std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(), + ..Default::default() + }, + |ui| { + let viewport = ui.max_rect(); + show(&mut h.app, ui); + environment_overlay(&mut h.app, ui, viewport); + }, + ); + output.textures_delta.clear(); +} + +fn environment_ring_fixture() -> Harness { + let mut h = environment_editor_fixture(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.preferences.nav = crate::prefs::OPENSCAD_NAV.into(); + h.app.cam.fit(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap().bounds); + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + h +} + +#[test] +fn render_workspace_frame_rect_fits_centres_and_refuses_hostile_sizes() { + let viewport = egui::Rect::from_min_size(egui::pos2(100.0, 40.0), egui::vec2(800.0, 600.0)); + for aspect in [16.0 / 9.0, 1.5, 1.0, 0.8, 9.0 / 16.0, 0.01, 100.0] { + let frame = shot::frame_rect(aspect, viewport).unwrap(); + assert!(viewport.contains_rect(frame)); + assert_eq!(frame.center(), viewport.center()); + assert!((f64::from(frame.width() / frame.height()) - aspect).abs() < 0.001); + assert!(frame.width() == viewport.width() || frame.height() == viewport.height()); + } + for aspect in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::MAX, 1e-300] { + assert!(shot::frame_rect(aspect, viewport).is_none()); + } + for size in [egui::Vec2::ZERO, egui::vec2(0.0, 400.0), egui::vec2(f32::NAN, 10.0), egui::vec2(f32::MAX, f32::MAX), egui::vec2(-10.0, 20.0)] { + assert!(shot::frame_rect(1.5, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none()); + } +} + +fn frame_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1200})); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"width":800,"height":600,"camera":h.app.cam}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h +} + +#[test] +fn environment_ring_drag_is_one_undo_snaps_and_never_navigates_the_camera() { + use egui::{Event, Modifiers, PointerButton}; + let mut h = environment_ring_fixture(); + environment::commit_environment(&mut h.app, json!({"rotation_deg":170})).unwrap(); + environment_ring_frame(&mut h, Modifiers::NONE, vec![]); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let at = |degrees: f32| ring.center + egui::vec2(degrees.to_radians().cos(), degrees.to_radians().sin()) * ring.radius; + let press = at(0.0); + let before = h.app.session.doc.clone(); + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + for pressed in [true, false] { + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }, + ], + ); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "a Shift click without a drag does not snap or save"); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + for angle in [10.0, 20.0, 30.0] { + environment_ring_frame(&mut h, Modifiers::SHIFT, vec![Event::PointerMoved(at(angle))]); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "drag is temporary"); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera, "OpenSCAD left-drag must not orbit through the ring"); + } + let end = at(30.0); + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::SHIFT }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!((h.app.render_workspace.view.studio.rotation_rad.to_degrees() + 165.0).abs() < 1e-6); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert!(crate::scenario::rect_of("render:environment:ring-degrees").is_some()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_ring_cancel_or_stale_revision_discards_the_drag() { + use egui::{Event, Modifiers, PointerButton}; + for stale in [false, true] { + let mut h = environment_ring_fixture(); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let start = ring.center + egui::vec2(ring.radius, 0.0); + let end = ring.center + egui::vec2(0.0, ring.radius); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(end)]); + if stale { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":640}})).unwrap(); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + let cancel = if stale { + vec![] + } else { + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }] + }; + environment_ring_frame(&mut h, Modifiers::NONE, cancel); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(start)]); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], + ); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn environment_ring_visibility_follows_editor_target_and_live_canvas() { + let mut h = environment_ring_fixture(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.app.render_workspace.view.selection = RenderSelection::Environment; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_some()); + h.app.render_workspace.view.selection = RenderSelection::Nothing; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.render_workspace.view.result = true; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); +} + +#[test] +fn environment_editor_opening_pages_and_sources_preserves_design_and_history() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for page in [inspector::Page::Environment, inspector::Page::Background] { + h.app.render_workspace.view.inspector.page = page; + environment_editor_frame(&mut h, vec![]); + assert!(crate::scenario::rect_of("render:environment:rotation-slider").is_some()); + h.app.ui.show_browser = false; + environment::open_sources(&mut h.app); + assert!(h.app.ui.show_browser); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn environment_editor_controls_commit_one_undo_each_and_refuse_hostile_edits() { + let mut h = environment_editor_fixture(); + for request in [json!({"rotation_deg":215}), json!({"intensity":2.5})] { + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + } + for (color, transparent) in [([40, 80, 120], false), ([40, 80, 120], true), ([40, 80, 120], false)] { + let undo = h.app.session.undo.len(); + environment::commit_backdrop(&mut h.app, color, transparent).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let mut ground = environment::Ground { margin: 0.25, gap: 0.1, color: [0.18; 3] }; + for edit in 0..5 { + match edit { + 1 => ground.margin = 1.0, + 2 => ground.gap = 0.25, + 3 => ground.color = [0.1, 0.3, 0.5], + _ => {} + } + let undo = h.app.session.undo.len(); + environment::commit_ground(&mut h.app, edit != 4, ground.clone()).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for request in [json!({"rotation_deg":1e300}), json!({"intensity":-1}), json!({"rotation_deg":"NaN"}), json!(null), json!([])] { + assert!(environment::commit_environment(&mut h.app, request).is_err()); + } + assert!(environment::commit_ground(&mut h.app, true, environment::Ground { gap: f64::NAN, ..ground }).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn environment_editor_slider_drag_commits_only_on_release() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let rect = crate::scenario::rect_of("render:environment:rotation-slider").unwrap(); + let start = rect.center(); + let end = egui::pos2(rect.right() - 20.0, start.y); + let undo = h.app.session.undo.len(); + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(start), + egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + ], + ); + environment_editor_frame(&mut h, vec![egui::Event::PointerMoved(end)]); + assert_eq!(h.app.session.undo.len(), undo, "dragging is temporary"); + environment_editor_frame( + &mut h, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1, "release saves one edit"); + environment_editor_frame(&mut h, vec![]); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_hdr_header_reads_catalog_without_applying_or_saving() { + let mut h = environment_editor_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(305.0, 1600.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let named = crate::test_support::text_shapes(&output).any(|text| text.galley.job.text.contains("Neutral side softbox")); + output.textures_delta.clear(); + assert!(named); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for request in [json!({"rotation_deg":540}), json!({"intensity":0})] { + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } +} + +#[test] +fn render_workspace_frame_opening_editor_and_presets_never_mutates_or_starts_a_job() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + h.frames(4); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(crate::scenario::rect_of("render:shot:name").is_some()); + assert!(crate::scenario::rect_of("render:frame:aspect:16:9").is_some()); + assert!(crate::scenario::rect_of("render:frame:overlay").is_some()); + assert_eq!(shot::selected(&h.app), Some("Hero")); + h.step(&json!({"click":{"handle":"render:frame:thirds"}})).unwrap(); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + let mut h = frame_editor_fixture(); + let camera = Camera { fov: 175f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.frames(4); + assert_eq!(h.app.cam, camera, "opening must preserve valid FOVs outside the slider's usual editing range"); +} + +#[test] +fn render_workspace_frame_guides_are_transient_and_overlay_visibility_is_contextual() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.run("view.render_frame", json!({"aspect":"16:9","thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + assert!(shot::overlay_visible(&h.app)); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)); + let frame = shot::preview_rect(&h.app, viewport).unwrap(); + assert!((frame.width() / frame.height() - 16.0 / 9.0).abs() < 0.001); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + assert!(!shot::overlay_visible(&h.app)); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + assert!(shot::overlay_visible(&h.app)); + h.app.render_workspace.view.result = true; + assert!(!shot::overlay_visible(&h.app)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.doc.render.setups["Hero"].width, 800); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert!(h.app.render_workspace.view.frame.guides.safe_area); + assert!(h.app.render_workspace.view.frame.guides.centre_mark); +} + +#[test] +fn render_workspace_frame_exposure_drag_is_one_saved_edit_and_undoes() { + let mut h = frame_editor_fixture(); + shot::edit_settings(&mut h.app, "Hero", json!({"job":{"method":"cpu_raytrace"}})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0, "exposure track: {track:?}"); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + assert_ne!( + h.app.session.doc.render.setups["Hero"].exposure_ev, 0.0, + "track: {track:?}; state: {:?}; status: {:?}", + h.app.render_workspace.view.frame, h.app.status + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +#[test] +fn render_workspace_scene_render_shot_captures_current_size_and_live_camera_without_saving() { + let mut h = frame_editor_fixture(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + shot::edit_settings(&mut h.app, "Hero", json!({"width":16,"height":12})).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = Camera { distance: 85.0, fov: 35f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.app.run("view.render_frame", json!({"thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Hero")); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16384).unwrap(); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().unwrap(); + assert_eq!((frame.info.width, frame.info.height), (16, 12)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_frame_aspect_click_edits_only_selected_shot_size_once_and_undoes() { + let mut h = frame_editor_fixture(); + h.frames(4); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:frame:aspect:16:9"}})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), (1920, 1080)); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + for (index, expected) in [(1, (1620, 1080)), (2, (1080, 1080)), (3, (864, 1080)), (4, (1080, 1920))] { + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", index).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), expected); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", 5).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(shot::choose_aspect(&mut h.app, "Hero", usize::MAX).is_err()); +} + +#[test] +fn render_workspace_frame_shot_edits_revert_duplicate_and_rename_use_existing_commands() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.render.setups["Hero"].clone(); + let camera = Camera { distance: before.camera.distance * 2.0, ..before.camera }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + let undo = h.app.session.undo.len(); + assert!(shots::camera_modified(&h.app, "Hero")); + shot::edit_settings(&mut h.app, "Hero", json!({"camera":camera})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(!shots::camera_modified(&h.app, "Hero")); + h.app.run("edit.undo", json!({})).unwrap(); + shot::revert(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.cam, before.camera); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + shot::duplicate(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + let copied = h.app.session.doc.render.setups.iter().find(|(name, _)| name.as_str() != "Hero").unwrap().1; + assert_eq!(copied, &h.app.session.doc.render.setups["Hero"]); + shot::rename(&mut h.app, "Hero", "Renamed").unwrap(); + assert_eq!(shot::selected(&h.app), Some("Renamed")); + assert_eq!(h.app.session.undo.len(), undo + 3); + let before = h.app.session.doc.to_json(); + for patch in [json!({"width":0}), json!({"width":u32::MAX}), json!({"height":1e300}), json!({"exposure_ev":33}), json!({"exposure_ev":null})] { + assert!(shot::edit_settings(&mut h.app, "Renamed", patch).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + } +} + +fn render_lights_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"cpu_raytrace","options":{"lights":[ + {"direction":[0.6,0,0.8],"color":[1,0.5,0.25],"intensity":3}, + {"direction":[-0.8,0,0.6],"color":[0.25,0.5,1],"intensity":2} + ]}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + setups::load(&mut h.app); + h.app.pending_fit = None; + h +} + +#[test] +fn render_lights_solo_and_mute_filter_preview_and_render_copies_without_saving_or_history() { + let mut h = render_lights_fixture(); + let original = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let json = document.to_json(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + assert_eq!(light::preview(&h.app).unwrap().len(), 1); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["lights"][0]["intensity"], 0.0); + assert_eq!(request["settings"]["job"]["options"]["lights"][1]["intensity"], 2.0); + h.app.run("render.lights.mute", json!({"id":"directional:1","mute":true})).unwrap(); + assert!(light::preview(&h.app).unwrap().is_empty()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["lights"][1]["intensity"], 0.0); + assert_eq!(setups::snapshot(&h.app).unwrap(), original); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.doc.to_json(), json); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + assert!(h.app.run("render.lights.mute", json!({"id":"area:0","mute":true})).is_err()); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.active()); +} + +#[test] +fn render_lights_editor_opening_and_disabled_gpu_types_never_edit_or_start_a_job() { + let mut h = render_lights_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{"area_lights":[ + {"center":[0,0,100],"u":[1000000,0,0],"v":[0,-1000000,0],"radiance":[0,0,0]} + ]}}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + h.step(&json!({"click":{"handle":"render:light:type:point"}})).unwrap(); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); + assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "area"); +} + +#[test] +fn render_lights_edit_commands_refresh_selected_editor_and_keep_visibility_separate_from_undo() { + let mut h = render_lights_fixture(); + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + light::edit(&mut h.app, "render.lights.set", Some("directional:0"), Some(json!({"intensity_ev":2}))).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 4.0); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, document); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 3.0); + light::edit(&mut h.app, "render.lights.duplicate", Some("directional:0"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:2".into())); + light::edit(&mut h.app, "render.lights.remove", Some("directional:2"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); +} + +#[test] +fn render_lights_fixed_studio_requests_carry_transient_weights_without_saving_them() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + let raster = image_request(&h.app).unwrap(); + assert_eq!(raster["studio_weights"], json!([0.0, 1.0, 0.0])); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + assert_eq!(image_request(&h.app).unwrap()["studio_weights"], json!([0.0, 1.0, 0.0])); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + assert!(serde_json::to_value(setups::snapshot(&h.app).unwrap()).unwrap().get("studio_weights").is_none()); +} + +#[test] +fn render_lights_list_inspects_unsaved_ui_draft_without_applying_or_opening_anything() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = + Some(vec![solidcraft_engine::render::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 7.0 }]); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + let camera = h.app.cam; + let page = h.app.render_workspace.view.inspector.page; + let snapshot = setups::snapshot(&h.app).unwrap(); + let reply = h.app.run("render.lights.list", json!({"settings":snapshot})).unwrap(); + assert_eq!(reply["lights"].as_array().unwrap().len(), 1); + assert_eq!(reply["lights"][0]["id"], "directional:0"); + assert_eq!(reply["lights"][0]["name"], "Key"); + assert_eq!(reply["lights"][0]["intensity"], 7.0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert_eq!(setups::snapshot(&h.app).unwrap(), snapshot); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +mod async_path_host { + + #[test] + fn cpu_and_raster_render_entries_keep_gpu_setup_unstarted_across_document_reset() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + h.app.render_workspace.defer_path_host("not requested".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("a CPU/Raster method must not call this GPU factory".into()) + }); + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + enter(&mut h.app, true).unwrap(); + for _ in 0..3 { + sync_backend(&mut h.app); + } + // The synchronous state and retained factory prove that no worker was + // launched, even if a wrongly launched thread had not been scheduled yet. + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + + crate::documents::adopt(&mut h.app, Session::default()); + select_image_method(&mut h.app, method); + enter(&mut h.app, true).unwrap(); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("not requested")); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + } + + #[test] + fn explicit_gpu_selection_starts_once_and_keeps_its_receiver_across_document_changes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let (started, seen) = mpsc::channel(); + let (release, wait) = mpsc::channel(); + h.app.render_workspace.defer_path_host("explicit request".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + started.send(()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + Err("deliberate device-free refusal".into()) + }); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + seen.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + // A real in-progress factory is not abandoned or duplicated when a new + // document defaults back to Raster, or the user changes methods meanwhile. + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + let duplicate_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not duplicate".into(), move || { + duplicate_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected duplicate preparation".into()) + }); + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + release.send(()).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("expected deliberate refusal") }; + assert_eq!(error, "deliberate device-free refusal"); + + // A method change or new document does not become an automatic retry. + crate::documents::adopt(&mut h.app, Session::default()); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("document reset lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("GPU selection lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + let retry_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not retry".into(), move || { + retry_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected replacement after terminal failure".into()) + }); + sync_backend(&mut h.app); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("terminal failure was replaced") }; + assert_eq!(error, "deliberate device-free refusal"); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + use super::*; + use solidcraft_engine::render::job; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + /// Advertise the path capability without opening a device or rendering anything. + struct TestExecutor; + impl job::ImageExecutor for TestExecutor { + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("test-path").unwrap(); + descriptor.profiles[0].features.push(solidcraft_engine::render::RenderFeature::Progressive); + Ok(descriptor) + } + fn admit(&self, _: &ProductScene, _: &job::ImageRequest, _: job::JobOptions) -> job::Result { + panic!("setup tests must not render") + } + fn begin(&self, _: ProductScene, _: job::ImageRequest, _: job::JobOptions, _: job::CancelToken) -> job::Result> { + panic!("setup tests must not render") + } + } + + fn panel_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h + } + + fn finish_setup(h: &mut Harness) { + let deadline = Instant::now() + Duration::from_secs(10); + while matches!(h.app.render_workspace.path_host, PathHost::Preparing(..)) { + assert!(Instant::now() < deadline, "test setup worker did not finish"); + h.frames(1); + std::thread::sleep(Duration::from_millis(1)); + } + h.frames(3); + } + + #[test] + fn design_frames_and_document_reset_never_start_the_deferred_path_host() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(5); + crate::documents::adopt(&mut h.app, Session::default()); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn first_render_before_adapter_install_starts_once_when_the_adapter_arrives() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = panel_fixture(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + h.app.render_workspace.defer_path_host("late selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("deliberate device refusal".into()) + }); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + h.app.render_workspace.defer_path_host("must not retry".into(), || panic!("failed setup retried")); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_fallback_viewport_replaces_an_unstarted_factory_without_opening_the_old_device() { + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("old hardware adapter".into(), || panic!("superseded device opened")); + h.app.render_workspace.defer_path_host("selected safe-mode adapter".into(), || Err("selected adapter unavailable".into())); + h.frames(5); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("selected safe-mode adapter")); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("expected selected adapter result") }; + assert_eq!(message, "selected adapter unavailable"); + } + + #[test] + fn preparing_keeps_frames_responsive_then_registers_ready_host() { + let mut h = panel_fixture(); + let cpu_host = h.app.session.render_job_host().unwrap().clone(); + let (release, wait) = mpsc::channel(); + let (started, thread) = mpsc::channel(); + h.app.render_workspace.path_host.start(move || { + started.send(std::thread::current().id()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + assert_ne!(thread.recv_timeout(Duration::from_secs(10)).unwrap(), std::thread::current().id()); + // A second viewport installation cannot replace or duplicate setup. + h.app.render_workspace.path_host.start(|| panic!("setup started twice")); + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(!h.app.session.render_backend().executors.iter().any(|e| e.id.as_str() == "test-path")); + let transparent = h.app.tr("render.image_transparent").to_string(); + h.step(&json!({"widget":transparent})).unwrap(); + assert!(h.app.render_workspace.view.transparent); + // Replacing the current document must retain the receiver while setup waits. + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + enter(&mut h.app, false).unwrap(); + release.send(()).unwrap(); + finish_setup(&mut h); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_ok()); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + assert!(h.app.session.render_job_host().unwrap().same_host(&cpu_host)); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + } + + /// The first setup on an adapter shows a spinner, the time so far and a note; a later one + /// a bar estimated from the time the first took, which the preferences keep. + #[test] + fn setup_progress_is_estimated_from_the_last_setup_on_the_adapter() { + let mut h = panel_fixture(); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + let first = h.app.tr("render.gpu_path_first_setup").to_string(); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(h.widget(&first).is_some(), "the first setup explains the wait"); + assert!(h.widget("0:00").is_some(), "and counts the time"); + release.send(()).unwrap(); + finish_setup(&mut h); + let took = h.app.render_workspace.setup_seconds.get("Test GPU | Vulkan | 1.0").copied(); + assert!(took.is_some_and(|s| (0.0..10.0).contains(&s)), "{took:?}"); + + // The next start on the same adapter has an estimate, kept in the preferences. + let mut h = panel_fixture(); + h.app.load_prefs(&json!({"gpu_path_setup_seconds": {"Test GPU | Vulkan | 1.0": 120.0}}).to_string()); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + assert!(h.widget(&first).is_none()); + assert!(h.widget("0:00 / ~2:00").is_some(), "a bar with the estimate"); + release.send(()).unwrap(); + finish_setup(&mut h); + let prefs: serde_json::Value = serde_json::from_str(&h.app.prefs()).unwrap(); + assert!(prefs["gpu_path_setup_seconds"]["Test GPU | Vulkan | 1.0"].as_f64().is_some_and(|s| s < 10.0)); + } + + #[test] + fn hostile_setup_times_are_ignored() { + let times = load_setup_seconds(&json!({"a": -1.0, "b": 1e300, "c": "slow", "d": 30.0})); + assert_eq!(times.into_iter().collect::>(), [("d".to_string(), 30.0)]); + let many: serde_json::Map = (0..100).map(|i| (format!("gpu {i}"), json!(1.0))).collect(); + assert_eq!(load_setup_seconds(&serde_json::Value::Object(many)).len(), MAX_SETUP_TIMES); + } + + #[test] + fn setup_error_is_visible_and_survives_document_reset() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| Err("test driver refused the device".into())); + finish_setup(&mut h); + let message = "GPU path tracer unavailable: test driver refused the device"; + assert!(h.widget(message).is_some()); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(h.app.session.render_job_host().is_some()); + completed_preview(&mut h, [200, 210, 220]); + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget(message).is_some()); + h.app.render_workspace.path_host.start(|| panic!("failed setup retried on viewport install")); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + } + + #[test] + fn disconnected_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + let (tx, rx) = mpsc::channel(); + h.app.render_workspace.path_host = PathHost::Preparing(rx, Instant::now()); + drop(tx); + h.frames(3); + assert!(h.widget("GPU path tracer unavailable: setup worker stopped without returning a host").is_some()); + } + + #[test] + fn panicking_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| panic!("simulated driver panic")); + finish_setup(&mut h); + assert!(h.widget("GPU path tracer unavailable: GPU path tracer setup panicked").is_some()); + } + + #[test] + fn registration_failure_is_reported_in_the_panel() { + let mut h = panel_fixture(); + // A different host with the same CPU descriptor cannot be registered twice. + h.app.render_workspace.path_host.start(|| Ok(job::CpuHost::cooperative())); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("duplicate executor must fail") }; + assert!(h.widget(&format!("GPU path tracer unavailable: {message}")).is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opaque_pbr_product_gpu_and_cpu_share_color_and_material_semantics() { + use solidcraft_engine::render::{ + StandardView, + job::{CancelToken, ImageRequest, ImageTask, TaskPoll}, + }; + let mut s = Session::default(); + s.execute("solid.sphere", &json!({"radius":10,"body_name":"Original sphere"})).unwrap(); + const SIZE: u32 = 256; + let mut previous = None; + for (metallic, roughness) in [(0.0, 0.2), (0.0, 0.65), (1.0, 0.2), (1.0, 0.65)] { + s.execute( + "appearance.assign", + &json!({"bodies":["Original sphere"],"color":"#b47846", + "pbr":{"metallic":metallic,"roughness":roughness,"dielectric_ior":1.5}}), + ) + .unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(!gpu.pbr.is_empty() && gpu.tris.is_empty()); + assert_ne!(previous, Some(key)); + previous = Some(key); + let mut camera = Camera { fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Iso); + camera.fit(&scene.bounds); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let mut task = ImageTask::new( + scene, + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera, + width: SIZE, + height: SIZE, + background: [255; 3], + transparent_background: false, + integrator: Default::default(), + raytrace: None, + }, + CancelToken::default(), + ) + .unwrap(); + let mut png = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() { + png = Some(bytes); + break; + } + } + let cpu = image::load_from_memory(&png.expect("bounded original fixture completes")).unwrap().to_rgba8(); + assert_eq!(cpu.dimensions(), (SIZE, SIZE)); + let cpu = cpu.into_raw(); + for srgb in [false, true] { + let Some(gpu) = crate::gpu::render_product_offscreen( + gpu.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 0.0], + SIZE, + srgb, + ) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let at = |pixels: &[u8], x: usize, y: usize| { + let i = (y * SIZE as usize + x) * 4; + [pixels[i], pixels[i + 1], pixels[i + 2]] + }; + let mut core = 0usize; + let mut error = 0usize; + let mut outliers = 0usize; + for y in 2..SIZE as usize - 2 { + for x in 2..SIZE as usize - 2 { + // Exclude antialiased silhouettes: CPU uses 2x supersampling, GPU uses 1x. + if (y - 1..=y + 1).any(|ny| (x - 1..=x + 1).any(|nx| at(&cpu, nx, ny) == [255; 3] || at(&gpu, nx, ny) == [255; 3])) { + continue; + } + let delta = at(&cpu, x, y).into_iter().zip(at(&gpu, x, y)).map(|(a, b)| usize::from(a.abs_diff(b))).collect::>(); + error += delta.iter().sum::(); + outliers += usize::from(delta.iter().any(|d| *d > 12)); + core += 1; + } + } + assert!(core > 1000); + let mean = error as f64 / (3 * core) as f64; + eprintln!("PBR m={metallic} r={roughness} srgb={srgb}: core={core}, mean={mean}, outliers={outliers}"); + assert!(mean < 2.0 && outliers * 100 < core * 2, "CPU/GPU color or material interpretation differs"); + } + } +} + +#[test] +fn control_render_export_respects_upstream_file_scope() { + let mut h = Harness::new(); + let root = h.dir.join("allowed"); + let outside = h.dir.join("outside"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let roots = json!([root.to_string_lossy()]); + let response = h.call("ui.workspace", json!({"workspace":"render","allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let response = h.call("engine.execute", json!({"command":"render.start","params":{"settings":{"width":16,"height":16}},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let job = response["result"]["job"].clone(); + for _ in 0..50 { + h.frames(1); + } + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); + for path in [outside.join("denied.png"), root.join("../outside/traversal.png")] { + for overwrite in [false, true] { + let response = h.call( + "engine.execute", + json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":overwrite},"allow_paths":roots}), + ); + assert_eq!(response["ok"], false, "{response}"); + assert!(response.to_string().contains("outside the folders this agent may use"), "{response}"); + } + } + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + let path = root.join("allowed.png"); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert!(path.is_file()); + let original = std::fs::read(&path).unwrap(); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":true},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(std::fs::read(&path).unwrap(), original); +} + +#[test] +fn adopting_into_blank_document_resets_render_draft_and_preserves_hosts() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.render_workspace.view.name = "Old draft".into(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let mut incoming = Session::default(); + incoming.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + crate::documents::adopt(&mut h.app, incoming); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + assert!(h.app.session.render_job_host().is_some()); + assert_eq!(h.app.session.model.state().bodies.len(), 1); +} + +#[test] +fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.frames(1); + let check = h.app.tr("cmd.render_preflight").to_string(); + let start = h.app.tr("render.image_start").to_string(); + let export = h.app.tr("render.image_export").to_string(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":check})).unwrap(); + h.step(&json!({"widget":start})).unwrap(); + for _ in 0..50 { + h.frames(1); + if h.app.render_workspace.view.completed.is_some() { + break; + } + } + let good = h.app.render_workspace.view.completed.unwrap(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 768; + h.step(&json!({"widget":start})).unwrap(); + assert!(job_ready(&h.app, "render.cancel").is_ok()); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(5); + assert_eq!(h.app.render_workspace.view.completed, Some(good)); + assert_eq!( + h.app.session.execute("render.status", &json!({"job":h.app.render_workspace.view.job})).unwrap()["progress"]["phase"], + "cancelled" + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn saved_camera_survives_frames_and_product_fit_ignores_selection() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Product"})).unwrap(); + h.app.run("solid.box", json!({"corner":[100,0,0],"length":10,"width":20,"height":5,"body_name":"Other"})).unwrap(); + let camera = Camera { up: solidcraft_engine::render::UpAxis::Y, roll: 0.2, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":camera,"background":[21,43,65]}})).unwrap(); + h.frames(3); + let design = h.app.cam; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h.step(&json!({"widget":"Restore Saved Camera"})).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.background, [21, 43, 65]); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Product".into() }]; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + let selected_fit = h.app.cam; + assert_product_fits_canvas(&h.app); + h.app.session.selection.clear(); + h.app.cam = camera; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + assert_eq!(h.app.cam, selected_fit, "Fit Product ignores the selected subset"); + enter(&mut h.app, false).unwrap(); + assert_eq!(h.app.cam, design); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn progressive_image_controls_route_to_the_registered_host() { + let host = solidcraft_gpu::select::Policy::from_env() + .and_then(|policy| solidcraft_gpu::select::pick(policy).ok_or_else(|| "no qualifying adapter".to_string())) + .and_then(|(adapter, _)| solidcraft_gpu::path::host_on_adapter(&adapter).map_err(|e| e.to_string())); + let host = match host { + Ok(host) => host, + Err(e) => { + let expected = !solidcraft_gpu::select::path_backends().is_empty(); + assert!(!expected || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}"); + eprintln!("skipping progressive UI device test: {e}"); + return; + } + }; + let mut h = Harness::new(); + h.app.render_workspace.path_host = PathHost::Ready(host); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.samples = 4; + h.app.render_workspace.view.max_depth = 3; + h.app.render_workspace.view.seed = 7; + h.app.render_workspace.view.draft.exposure_ev = 0.5; + h.app.render_workspace.view.studio.tone_map = solidcraft_engine::render::job::ToneMap::AcesFitted; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.studio.lens.aperture_radius_mm = 0.0; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.ambient = [0.75; 3]; + // The UI request reaches the real registered host with a coat and captured map. + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut material = materials::Binding::new(target, &h.app); + material.coat_enabled = true; + material.maps_enabled = true; + let map_path = h.dir.join("original-color.png"); + image::RgbaImage::from_pixel(1, 1, image::Rgba([80, 160, 220, 255])).save(&map_path).unwrap(); + material.maps.color = map_path.to_string_lossy().into_owned(); + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(material); + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + let checked = image_params(&h.app).unwrap(); + assert_eq!(checked["raytrace"]["clear_coats"][0]["weight"], 1.0); + assert_eq!(checked["raytrace"]["textures"][0]["base_color_srgb"], map_path.to_string_lossy().as_ref()); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while h.app.render_workspace.view.completed.is_none() { + assert!(std::time::Instant::now() < deadline, "progressive UI job did not complete"); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.frames(1); + } + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["frame"]["executor"], "gpu-path", "{status}"); + assert_eq!(status["options"]["samples"], 4); + assert_eq!(status["options"]["max_depth"], 3); + assert_eq!(status["options"]["seed"], 7); + assert_eq!(status["options"]["exposure_ev"], 0.5); + assert_eq!(status["options"]["tone_map"], "aces_fitted"); + assert_eq!(status["options"]["lens"]["aperture_radius_mm"], 0.0); + assert_eq!(status["options"]["lighting"]["environment"], json!([0.75, 0.75, 0.75])); + assert_eq!(status["textures"]["bodies"], 1); + let export = h.app.tr("render.image_export").to_string(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + // A pack glass recipe follows the same production request and passes actual + // closed-mesh preparation. It never calls scalar appearance assignment. + let material = &mut h.app.render_workspace.view.materials.bindings[0]; + material.coat_enabled = false; + material.maps_enabled = false; + material.glass_enabled = true; + material.glass = materials::Glass::recipe("starter.glass.clear-soda-lime").unwrap(); + let checked = image_params(&h.app).unwrap(); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let started = h.app.run("render.start", checked).unwrap(); + let job = serde_json::from_value(started["job"].clone()).unwrap(); + let status = h.app.session.render_job_handle(job).unwrap().wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_engine::render::job::Phase::Completed, "{:?}", status.error); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_render_workspace_saves_one_setup_and_restores_design_view() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.frames(3); + let camera = h.app.cam; + let flags = (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective); + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("workspace_switcher").unwrap().center(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + h.step(&json!({"click":{"handle":"menu:ui.workspace.render"}})).unwrap(); + assert!(active(&h.app)); + let heading = h.app.tr("render.page_scene").to_string(); + let perspective = h.app.tr("render.perspective").to_string(); + let save = h.app.tr("render.save_setup").to_string(); + let back = h.app.tr("render.return_design").to_string(); + assert!(h.widget(&heading).is_some(), "{language}"); + h.step(&json!({"click":{"handle":"render:scene:frame"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Camera); + h.step(&json!({"widget":perspective})).unwrap(); + assert!(!h.app.session.is_dirty(), "preview edits are staged"); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["Studio"].camera, h.app.cam); + h.step(&json!({"widget":back})).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.cam, camera); + assert_eq!(flags, (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective)); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn render_drafts_and_capabilities_are_isolated_across_document_switches() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.render_workspace.view.name = "First draft".into(); + h.app.render_workspace.view.draft.background = [20, 40, 60]; + h.app.render_workspace.view.dirty = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.name, "First draft"); + assert_eq!(h.app.render_workspace.view.draft.background, [20, 40, 60]); + assert!(h.app.render_workspace.view.dirty); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + h.app.run("file.new", json!({})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); +} + +#[test] +fn product_gpu_buffers_preserve_opacity_and_never_contain_overlays() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(gpu.tris.is_empty()); + assert!(!gpu.glass.is_empty()); + let color = |v: &[u8]| { + let i = v.get(crate::gpu::TRI_SIZE - 4..).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; + gpu.palette.get(crate::gpu::PaletteIndex(i)) + }; + assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| color(v) == Some([51, 102, 153, 102]))); + assert!(gpu.lines.is_empty() && gpu.overlay.is_empty() && gpu.under.is_empty() && gpu.hidden.is_empty() && gpu.ghost.is_empty()); + s.selection = vec![solidcraft_engine::Sel::Body { name: "Glass".into() }]; + s.section = Some((solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::X)); + let after = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(gpu_scene(&after).unwrap().0, key); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.0})).unwrap(); + let invisible = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(invisible.meshes[0].opacity, 0.0); + let (_, empty) = gpu_scene(&invisible).unwrap(); + assert!(empty.tris.is_empty() && empty.glass.is_empty()); +} + +#[test] +fn transmission_uses_legacy_preview_buffers_and_invalidates_the_opaque_cache() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + let appearance = json!({"bodies":["Glass"],"color":"#336699", + "pbr":{"metallic":0,"roughness":0.1,"dielectric_ior":1.5}}); + s.execute("appearance.assign", &appearance).unwrap(); + let (opaque_key, opaque) = gpu_scene(&solidcraft_engine::product_scene::extract(&s).unwrap()).unwrap(); + assert!(!opaque.pbr.is_empty()); + let mut scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + scene.meshes[0].transmission = + Some(solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::ZERO, None).unwrap()); + let (glass_key, glass) = gpu_scene(&scene).unwrap(); + assert_ne!(opaque_key, glass_key); + assert!(glass.pbr.is_empty()); + assert!(!glass.tris.is_empty()); + scene.meshes[0].opacity = 0.4; + let (_, transparent) = gpu_scene(&scene).unwrap(); + assert!(transparent.pbr.is_empty()); + assert!(!transparent.glass.is_empty()); +} + +#[test] +fn host_profiles_advertise_only_installed_opaque_pbr_not_hdri_refraction_or_final() { + use solidcraft_engine::render::*; + let host = host_executor(512, true, 4).unwrap(); + assert_eq!(host.limits.max_dimension, 512); + assert_eq!(host.profiles.len(), 1); + assert_eq!(host.profiles[0].features, vec![RenderFeature::Pbr]); + assert!(host.profiles[0].formats.is_empty()); + let mut s = Session::default(); + s.set_render_viewport(Some(host)).unwrap(); + let mut request = RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width: 512, + height: 512, + format: None, + features: Vec::new(), + policy: Default::default(), + }; + assert_eq!(resolve_request(&[s.render_backend()], &request).unwrap().executor.as_str(), "gpu-viewport"); + request.features = vec![RenderFeature::Pbr]; + assert!(resolve_request(&[s.render_backend()], &request).is_ok()); + for unsupported in [RenderFeature::Hdri, RenderFeature::Refraction, RenderFeature::Progressive] { + request.features = vec![unsupported]; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + } + request.features.clear(); + request.width = 513; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + request.width = 512; + request.mode = RenderMode::Final; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + assert!(host_executor(1024, false, 1).unwrap().availability != Availability::Available); + assert!(host_executor(1024, true, 0).is_err()); +} + +fn completed_preview(h: &mut Harness, background: [u8; 3]) -> solidcraft_engine::render::job::JobId { + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":16,"height":16,"background":background}})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + host.pump(16384).unwrap(); + if h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("small cooperative image did not complete within the work budget"); +} + +fn image_panel_frame(app: &mut SolveApp, ctx: &egui::Context) -> egui::FullOutput { + ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(285.0, 1200.0))), ..Default::default() }, + |ui| image_controls(app, ui), + ) +} + +#[test] +fn completed_image_is_painted_once_available_and_upload_is_cached() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none()); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + let texture = texture.as_ref().unwrap(); + let id = texture.id(); + assert_eq!(*cached_job, job); + assert_eq!(texture.size(), [16, 16]); + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert!(pixels.pixels.iter().all(|p| *p == Color32::from_rgb(20, 40, 60))); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!( + ctx.tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| { matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty()) }) + ); + let mut output = image_panel_frame(&mut h.app, &ctx); + assert!(!output.textures_delta.set.contains_key(&id), "repaint must reuse the texture"); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let path = h.dir.join("displayed.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png(), "displaying the image must not change export bytes"); +} + +#[test] +fn completed_image_keeps_last_export_during_work_and_updates_for_the_next_job() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(first); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + let old_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + assert_eq!(*cached_job, second); + assert_ne!(texture.as_ref().unwrap().id(), old_texture); + assert!(output.textures_delta.free.contains(&old_texture)); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 42.0; + let framing = h.app.render_workspace.view.result_camera; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none(), "another document must not show this image"); + assert!(!h.app.render_workspace.view.result); + crate::documents::switch(&mut h.app, 0); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, second); + assert!(h.app.render_workspace.view.result); + assert_eq!(h.app.render_workspace.view.result_camera, framing); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + reset_document(&mut h.app); + assert!(h.app.render_workspace.image.is_none()); + assert!(!h.app.render_workspace.view.result); +} + +#[test] +fn completed_image_decoder_preserves_alpha_and_rejects_invalid_sizes_and_pngs() { + let mut png = std::io::Cursor::new(Vec::new()); + let pixels = image::RgbaImage::from_pixel(2, 1, image::Rgba([80, 120, 160, 128])); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + let decoded = decode_image(png.get_ref(), 2, 1).unwrap(); + assert_eq!(decoded.size, [2, 1]); + assert_eq!(decoded.pixels, vec![Color32::from_rgba_unmultiplied(80, 120, 160, 128); 2]); + for (width, height) in [(0, 1), (u32::MAX, 1), (4096, 4096), (1, 1), (3, 1)] { + assert!(decode_image(png.get_ref(), width, height).is_err(), "{width}x{height}"); + } + assert!(decode_image(b"invalid PNG", 2, 1).is_err()); +} + +#[test] +fn cpu_checkpoints_replace_only_the_provisional_texture_and_keep_final_export_and_framing() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(first); + h.app.render_workspace.view.job = Some(first); + cache_render_images(&mut h.app, &ctx); + let final_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let second = completed_preview(&mut h, [80, 100, 120]); + let frame = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.job = Some(second); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + assert_eq!(displayed_image(&h.app).unwrap().info.job, second); + assert!(displayed_image(&h.app).unwrap().preview.is_some()); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 123.0; + h.app.render_workspace.view.result_camera.target.x = 5.0; + let camera = h.app.render_workspace.view.result_camera; + let first_checkpoint = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + // Repeated or older metadata never re-decodes bytes, even if passed bad data. + cache_preview_frame(&mut h.app, &ctx, &info, b"must not decode again"); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), first_checkpoint); + info.frame_sequence = 2; + info.samples_per_pixel = 2; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + let newer = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + assert_ne!(newer, first_checkpoint); + info.frame_sequence = 1; + cache_preview_frame(&mut h.app, &ctx, &info, b"out of order"); + remember_displayed_job(&mut h.app, false); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().info.frame_sequence, 2); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), newer); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), final_texture); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + let path = h.dir.join("checkpoint-export-is-final.png"); + h.app.run("render.export", json!({"job":h.app.render_workspace.view.completed,"path":path})).unwrap(); + let retained = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), retained.png()); + // A final can arrive after the panel read a still-running status. The cached + // completed ID deliberately remains the old job until publication is sampled. + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(displayed_image(&h.app).unwrap().preview.is_none()); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().job, second); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free, "a subsequent status refresh must not refit the new final"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn cancelling_a_preview_returns_to_the_final_image_without_resetting_pan_or_export() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let final_job = completed_preview(&mut h, [30, 50, 70]); + h.app.render_workspace.view.completed = Some(final_job); + h.app.render_workspace.view.job = Some(final_job); + cache_render_images(&mut h.app, &ctx); + let frame = h.app.session.render_job_handle(final_job).unwrap().frame().unwrap().unwrap(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_none(), "a different job's checkpoint must be ignored"); + info.frame.job = pending; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.target.x = 12.0; + h.app.render_workspace.view.result_camera.distance = 87.0; + let camera = h.app.render_workspace.view.result_camera; + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert_eq!(displayed_image(&h.app).unwrap().info.job, final_job); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.view.completed, Some(final_job)); + assert!(h.app.run("render.export", json!({"job":pending,"path":h.dir.join("not-final.png")})).is_err()); + let path = h.dir.join("after-preview-cancel.png"); + h.app.run("render.export", json!({"job":final_job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + // Document adoption must also release a provisional texture without leaking it into a tab. + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_some()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(displayed_image(&h.app).is_none()); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn result_framing_fits_both_axes_and_actual_size_respects_display_pixels() { + let canvas = egui::Rect::from_min_size(egui::pos2(40.0, 80.0), egui::vec2(800.0, 500.0)); + for size in [[1920, 1080], [100, 4000], [16, 16]] { + for dpi in [1.0, 1.5, 2.0] { + let fit = result_camera(size, canvas, dpi, ResultScale::Fit); + assert!(fit.is_valid()); + let fitted = result_rect(fit, size, canvas); + assert!(canvas.contains_rect(fitted), "{size:?} at {dpi}: {fitted:?}"); + assert_eq!(fitted.center(), canvas.center()); + let actual = result_rect(result_camera(size, canvas, dpi, ResultScale::Actual), size, canvas); + assert!((actual.width() * dpi - size[0] as f32).abs() < 0.01); + assert!((actual.height() * dpi - size[1] as f32).abs() < 0.01); + } + } +} + +#[test] +fn result_canvas_paints_large_capture_reports_staleness_and_preserves_export() { + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let preview = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + let draw = |app: &mut SolveApp| { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(app, ui), + ); + out.textures_delta.clear(); + out + }; + let out = draw(&mut h.app); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let current = h.app.tr("render.result_current"); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == current)); + let identity = format!("{}:{}:{}", job.session, job.serial, job.generation); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text().contains(&identity))); + let image_bounds = ctx + .tessellate(out.shapes, out.pixels_per_point) + .iter() + .filter_map(|p| match &p.primitive { + egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id => { + Some(mesh.vertices.iter().fold(egui::Rect::NOTHING, |r, v| r.union(egui::Rect::from_min_max(v.pos, v.pos)))) + } + _ => None, + }) + .fold(egui::Rect::NOTHING, |a, b| a.union(b)); + assert!(image_bounds.width() > 240.0 && image_bounds.height() > 240.0, "{image_bounds:?}"); + assert_eq!(h.app.cam, preview); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.session.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + let out = draw(&mut h.app); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == h.app.tr("render.image_stale"))); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().scene_generation, frame.info.scene_generation); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), id); + let path = h.dir.join("result-canvas.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); +} + +#[test] +fn result_navigation_uses_shared_pan_zoom_and_leaves_product_camera_unchanged() { + use egui::{Event, Key, Modifiers, PointerButton, vec2}; + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.ui.perspective = true; + h.app.preferences.smooth_wheel_zoom = false; + h.app.preferences.zoom_reverse = false; + let preview = h.app.cam; + let draft = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let dirty = h.app.render_workspace.view.dirty; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut time = 0.0; + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let fitted = h.app.render_workspace.view.result_camera; + let p = h.app.viewport.rect.unwrap().center() + vec2(80.0, 20.0); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p)]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 3.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert!(h.app.render_workspace.view.result_camera.distance < fitted.distance); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + let before_pan = h.app.render_workspace.view.result_camera.target; + let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![space(true), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], + ); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p + vec2(40.0, -20.0))]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![ + Event::PointerButton { pos: p + vec2(40.0, -20.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + space(false), + ], + ); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_pan); + assert_eq!(h.app.render_workspace.view.result_camera.pitch, fitted.pitch); + assert_eq!(h.app.render_workspace.view.result_camera.yaw, fitted.yaw); + let before_key = h.app.render_workspace.view.result_camera.target; + assert!(crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::CTRL, false)); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_key); + assert!(!crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::NONE, false)); + for command in ["view.fit", "view.home"] { + h.app.render_workspace.view.result_camera.target.x += 20.0; + h.app.run(command, json!({})).unwrap(); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + assert_eq!(h.app.render_workspace.view.result_camera, fitted); + } + assert_eq!(h.app.cam, preview); + assert!(h.app.ui.perspective); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), draft); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_params(&h.app).unwrap()["settings"]["camera"], json!(preview)); +} + +#[test] +fn clicked_result_controls_switch_canvas_and_frame_without_changing_the_setup() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let result = h.app.tr("render.result_title").to_string(); + h.step(&json!({"widget":result})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.result); + h.step(&json!({"widget":"100%"})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Actual); + let fit = h.app.tr("render.result_fit").to_string(); + h.step(&json!({"widget":fit})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Fit); + let preview = h.app.tr("render.result_preview").to_string(); + h.step(&json!({"widget":preview})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn image_method_requests_never_fall_back_or_mix_cpu_and_gpu_options() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = h.app.cam.distance * 3.0; + h.app.render_workspace.view.raytrace.exposure_ev = f64::NAN; + h.app.render_workspace.view.samples = 256; + h.app.render_workspace.view.max_depth = 12; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.draft.exposure_ev = 0.0; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "never-opened.hdr".into() }; + h.app.render_workspace.view.studio.denoise = true; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "never-opened-cpu.hdr".into() }; + let params = image_params(&h.app).unwrap(); + assert_eq!(params["settings"]["camera"], json!(h.app.cam)); + assert_eq!(params["settings"]["exposure_ev"], 0.0); + for key in ["progressive", "samples", "max_depth", "seed", "integrator", "raytrace", "environment", "lighting", "tone_map", "lens", "denoise"] { + assert!(params.get(key).is_none(), "raster must omit {key}"); + } + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert!(image_params(&h.app).is_err(), "missing GPU cannot silently render on CPU"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "unsupported CPU options or host must be refused"); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_params(&h.app).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_cpu_controls_check_and_start_the_same_capture_and_keep_it_exportable() { + use solidcraft_engine::render::job::{CpuHost, Phase}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-cpu"}})).unwrap(); + if !available { + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(image_params(&h.app).is_err()); + return; + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.step(&json!({"click":{"handle":"render:aa"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:aa-4"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + h.app.render_workspace.view.raytrace.preset = Some(LightingPreset::WarmCool); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let numeric = image_params(&h.app).unwrap(); + assert_eq!(numeric["settings"]["job"]["method"], "cpu_raytrace"); + assert!(numeric.get("raytrace").is_none()); + let numeric_check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":numeric_check})).unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, numeric); + let reflected = h.app.session.world_state().bodies.first().unwrap().name.clone(); + let reflection_section = format!("dialog:section:{}", h.app.tr("render.cpu_reflections")); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-body"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-add"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("render:cpu-reflection-mode:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render.cpu_reflection_mirror"}})).unwrap(); + assert_eq!( + h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().bodies[0].mode, + solidcraft_engine::render::job::ReflectionMode::Mirror + ); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + let hdr_path = h.dir.join("cpu-captured.hdr"); + let mut hdr = 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 1 +X 2\n".to_vec(); + hdr.extend_from_slice(&[128, 128, 128, 129, 128, 128, 128, 129]); + std::fs::write(&hdr_path, &hdr).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, hdr_path.to_string_lossy().into_owned()).unwrap(); + h.app.render_workspace.view.cpu.samples = 4; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = 42.0; + h.frames(2); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let params = image_params(&h.app).unwrap(); + let preflight = h.app.session.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace"); + let check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":check})).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), params); + let checked = h.app.render_workspace.view.cpu.checked.as_ref().unwrap(); + assert_eq!(checked.request, params); + assert_eq!(checked.environment, preflight["environment"]); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let id = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + // The job owns the source bytes captured by Start, even if the file changes. + std::fs::write(&hdr_path, b"changed after capture").unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(json!(status.environment), preflight["environment"]); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(json!(status.request.camera), params["settings"]["camera"]); + assert_eq!(json!(status.request.raytrace), params["raytrace"]); + assert_eq!(status.request.width, 16); + assert_eq!(status.request.height, 16); + h.frames(3); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + let path = h.dir.join("cpu-result-canvas.png"); + h.app.run("render.export", json!({"job":id,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + h.app.render_workspace.view.transparent = true; + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_opaque_required"))); + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.primary_samples = 3; + assert!(image_params(&h.app).is_err()); + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.area_lights = Some(Vec::new()); + assert_eq!(image_params(&h.app).unwrap()["raytrace"]["area_lights"], json!([])); +} + +fn async_export_fixture() -> (Harness, solidcraft_engine::render::job::JobId) { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + let job = completed_preview(&mut h, [200, 210, 220]); + (h, job) +} + +#[test] +fn delayed_image_export_holds_its_document_without_changing_history() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("delayed.png"); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy() && !path.exists()); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], true); + crate::documents::new_design(&mut h.app); + let other = h.app.session.doc.clone(); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.docs.active, 0, "upstream holds tab changes while a picker is pending"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], false); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert_eq!(&std::fs::read(&path).unwrap()[..8], b"\x89PNG\r\n\x1a\n"); + crate::documents::switch(&mut h.app, 0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn delayed_image_export_cancel_and_overwrite_choice_preserve_existing_files() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("existing.png"); + std::fs::write(&path, b"existing contents").unwrap(); + let doc = h.app.session.doc.clone(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!h.app.file_picker_busy()); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents"); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + h.app.render_workspace.view.overwrite = true; + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents", "a later checkbox change is not overwrite consent for the pending export"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); +} + +#[test] +fn delayed_image_export_never_substitutes_a_newer_retained_image() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("old-image.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + let newer = completed_preview(&mut h, [20, 30, 40]); + h.app.render_workspace.view.completed = Some(newer); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists(), "the evicted requested image must fail instead of exporting the newer image"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert_eq!(h.app.render_workspace.view.completed, Some(newer)); + let newer_path = h.dir.join("new-image.png"); + h.app.run("render.export", json!({"job":newer,"path":newer_path})).unwrap(); + assert!(newer_path.is_file()); +} + +#[test] +fn delayed_image_export_holds_close_and_new_document_until_cancel() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("closed.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + crate::documents::new_design(&mut h.app); + crate::documents::close(&mut h.app, 0, true); + let other = h.app.session.doc.clone(); + assert_eq!(h.app.docs.count(), 1); + assert!(h.app.file_picker_busy()); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists() && !h.app.file_picker_busy()); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); +} + +#[test] +fn delayed_image_export_refuses_an_internally_replaced_document_even_with_overwrite() { + use crate::picker_test_support::{Slot, save}; + for overwrite in [false, true] { + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("keep.png"); + std::fs::write(&path, b"keep this file").unwrap(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, overwrite); + assert!(h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":[1,2,3]})).is_err()); + // Internal host/session changes are outside the input hold; never export them by accident. + h.app.session.execute("appearance.assign", &json!({"bodies":["Body1"],"color":[1,2,3]})).unwrap(); + let changed = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.revision); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &crate::fonts::test_context()); + assert_eq!(std::fs::read(path).unwrap(), b"keep this file"); + assert!(Arc::ptr_eq(&changed, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.revision), history); + assert!(matches!(&h.app.status, Some((_, _, true)))); + } +} + +/// One frame of either the modelling viewport or the Render preview, over the same rectangle. +fn nav_frame(app: &mut crate::SolveApp, ctx: &egui::Context, render: bool, time: &mut f64, mods: egui::Modifiers, events: Vec) { + *time += 1.0 / 60.0; + let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if render { + show(app, ui); + } else { + crate::viewport::show(app, ui); + } + }); + out.textures_delta.clear(); +} + +fn nav_app(render: bool, preset: &str, around: crate::prefs::OrbitAround) -> crate::SolveApp { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + let mut app = crate::SolveApp::new(s, crate::Services::default()); + if render { + enter(&mut app, true).unwrap(); + assert!(active(&app)); + } + app.preferences.nav = preset.into(); + app.preferences.orbit_around = around; + app.preferences.zoom_to_cursor = true; + app.ui.perspective = true; + let mut cam = Camera { fov: 0.6, ..Default::default() }; + cam.set_view(solidcraft_engine::render::StandardView::Iso); + cam.fit(&solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds); + app.cam = cam; + app +} + +/// #1454: the same mouse, wheel and modifier input moves the Render preview's camera exactly as +/// it moves the modelling viewport's, under every navigation preset and Orbit around setting. +#[test] +fn render_preview_navigates_like_the_modelling_viewport_in_every_preset() { + use egui::{Event, Modifiers, PointerButton, pos2, vec2}; + let none = Modifiers::NONE; + let chords = [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT]; + let arounds = [crate::prefs::OrbitAround::ViewCentre, crate::prefs::OrbitAround::Cursor, crate::prefs::OrbitAround::Origin]; + for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { + for around in arounds { + let (design_ctx, render_ctx) = (crate::fonts::test_context(), crate::fonts::test_context()); + let mut design = nav_app(false, preset, around); + let mut render = nav_app(true, preset, around); + let (mut design_time, mut render_time) = (0.0, 0.0); + let mut both = |events: Vec, mods: Modifiers, design: &mut crate::SolveApp, render: &mut crate::SolveApp| { + nav_frame(design, &design_ctx, false, &mut design_time, mods, events.clone()); + nav_frame(render, &render_ctx, true, &mut render_time, mods, events); + }; + both(vec![], none, &mut design, &mut render); + assert_eq!(design.viewport.rect, render.viewport.rect); + // Presses start on empty space in both workspaces, and the wheel + // turns over the model, so zoom to the cursor anchors on its surface. + let empty = pos2(90.0, 520.0); + let proj = crate::viewport::projection(&design, design.viewport.rect.unwrap()); + assert!(crate::viewport::pick(&design, &proj, empty).is_empty()); + let model = proj.to_screen(design.cam.target).unwrap(); + assert!(!crate::viewport::pick(&design, &proj, model).is_empty()); + let mut moved = 0; + for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { + for mods in chords { + let before = design.cam; + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerButton { pos: empty, button, pressed: true, modifiers: mods }], mods, &mut design, &mut render); + let mut at = empty; + for _ in 0..5 { + at += vec2(14.0, -9.0); + both(vec![Event::PointerMoved(at)], mods, &mut design, &mut render); + } + both(vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: mods }], mods, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_eq!(design.cam, render.cam, "{preset} {around:?}: {button:?} drag with {mods:?}"); + moved += usize::from(design.cam != before); + // Let any snap settle and start the next gesture from the same view. + design.cam = render.cam; + } + } + assert!(moved >= 2, "{preset}: the preset's drags move the camera ({moved})"); + // Wheel over the model, then modifier-only motion (Touchpad: Shift pans, Alt orbits). + let before = design.cam; + both(vec![Event::PointerMoved(model)], none, &mut design, &mut render); + let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; + both(vec![wheel], none, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_ne!(design.cam, before, "{preset}: the wheel zooms"); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: wheel zoom to the cursor"); + for mods in [Modifiers::SHIFT, Modifiers::ALT] { + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty + vec2(25.0, 15.0))], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty)], none, &mut design, &mut render); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: modifier motion with {mods:?}"); + } + assert!(render.session.selection.is_empty(), "camera navigation must not select"); + } + } +} + +/// #1454: Fit (F6), a middle double-click, and the axis view's and navigation cube's Home and +/// view controls all work in the Render workspace, framing the product scene. +#[test] +fn render_workspace_view_keys_double_middle_click_and_navigators_work() { + for style in [crate::prefs::NavigatorStyle::Axes, crate::prefs::NavigatorStyle::Cube] { + let mut h = Harness::new(); + h.app.preferences.navigator_style = style; + h.app.preferences.look_at_anim = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let mut home = h.app.cam; + home.set_view(solidcraft_engine::render::StandardView::Iso); + let off = |h: &mut Harness| { + h.app.cam.yaw += 0.7; + h.app.cam.pitch = 0.1; + h.app.cam.distance *= 3.0; + h.app.cam.target.x += 25.0; + h.frames(2); + }; + // F6 fits, keeping the direction. + off(&mut h); + let before = h.app.cam; + h.step(&json!({"key":"F6"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (before.yaw, before.pitch, before.roll, before.up), + "{style:?}: F6 retains orientation" + ); + assert!(h.app.cam.distance < before.distance, "{style:?}: F6 frames the product"); + assert_product_fits_canvas(&h.app); + // A middle double-click goes Home. + off(&mut h); + let centre = h.app.viewport.rect.unwrap().center(); + h.step(&json!({"click":[centre.x, centre.y], "double":true, "button":"middle"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (home.yaw, home.pitch, home.roll, home.up), + "{style:?}: middle double-click" + ); + assert_product_fits_canvas(&h.app); + // The navigator's Home control. + off(&mut h); + let handle = match style { + crate::prefs::NavigatorStyle::Axes => "axis_view:home", + crate::prefs::NavigatorStyle::Cube => "navigation_cube:control:home", + }; + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.settle(); + assert!( + (h.app.cam.yaw - home.yaw).abs() < 1e-6 && (h.app.cam.pitch - home.pitch).abs() < 1e-6, + "{style:?}: navigator Home turns to the home view" + ); + // A standard view from the navigator. + h.step(&json!({"click":{"handle":"axis_view:z"}})).unwrap(); + h.settle(); + assert!(h.app.cam.back().dot(solidcraft_engine::geom::Vec3::Z) > 0.999, "{style:?}: view from +Z, got {:?}", h.app.cam.back()); + assert!(h.app.session.selection.is_empty()); + } +} + +/// #1464: a maximised 4K or 5K window is past the preview's pixel budget. The preview draws +/// smaller at the same aspect instead of refusing every frame. +#[test] +fn four_and_five_k_viewports_preview_downscaled_within_the_limits() { + use solidcraft_engine::render::*; + for samples in [1, 4, 16] { + let host = host_executor(16384, true, samples).unwrap(); + let mut s = Session::default(); + s.set_render_viewport(Some(host.clone())).unwrap(); + let request = |width, height| RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width, + height, + format: None, + features: vec![RenderFeature::Pbr], + policy: Default::default(), + }; + if samples <= 4 { + assert_eq!(preview_size(s.render_viewport(), (1920, 1080)), (1920, 1080), "fits: drawn at full size"); + } + // 16× MSAA's scratch cost brings even 1080p under the budget. + let sizes: &[(u64, u64)] = if samples == 16 { &[(1920, 1080), (3840, 2160), (5120, 2880)] } else { &[(3840, 2160), (5120, 2880)] }; + for &full in sizes { + assert!(resolve_request(&[s.render_backend()], &request(full.0, full.1)).is_err(), "{full:?} at full size is over the limit"); + let (w, h) = preview_size(s.render_viewport(), full); + assert!(w < full.0 && h < full.1 && w * h <= host.limits.max_pixels, "{full:?} -> {w}x{h}"); + assert!((w as f64 / h as f64 - 16.0 / 9.0).abs() < 0.01, "{w}x{h} keeps the aspect"); + let resolved = resolve_request(&[s.render_backend()], &request(w, h)).unwrap(); + assert_eq!(resolved.executor.as_str(), "gpu-viewport"); + assert!(resolved.estimated_scratch_bytes <= host.limits.max_scratch_bytes); + } + } + assert_eq!(preview_size(None, (5120, 2880)), (5120, 2880), "no executor: resolution reports it"); +} + +/// Backend failures must remain readable in the fixed-width Render panel, not +/// disappear into an ellipsis before the reason and recovery guidance are shown. +#[test] +fn backend_diagnostics_wrap_without_elision_in_bounded_image_controls() { + fn collect<'a>(shape: &'a egui::Shape, texts: &mut Vec<&'a egui::epaint::TextShape>) { + match shape { + egui::Shape::Text(text) => texts.push(text), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, texts)), + _ => {} + } + } + for mode in ["floating", "compact"] { + for dark in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1400,"height":1800})); + h.app.run("view.layout", json!({"mode":mode})).unwrap(); + enter(&mut h.app, true).unwrap(); + let reason = "The selected viewport adapter has no compatible Vulkan path device. Images remain available on the CPU; keep the original design and review the driver before retrying."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + h.frames(3); + let expected = format!("{}: {reason}", h.app.tr("render.gpu_path_failed")); + let mut out = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1800.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + ui.set_max_width(285.0); + image_controls(&mut h.app, ui); + }, + ); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|shape| collect(&shape.shape, &mut texts)); + { + let message = &expected; + let text = texts.iter().find(|text| text.galley.job.text == *message).expect("the complete diagnostic is painted"); + assert!(!text.galley.elided, "{mode}, dark={dark}: {message}"); + assert!(text.galley.rows.len() > 1, "long messages must wrap in the narrow panel"); + assert!(text.galley.rect.width() <= 285.0, "the message must not expand the panel"); + } + } + } +} + +#[test] +fn gpu_material_recipes_use_exact_linear_absorption_without_changing_saved_appearance() { + use solidcraft_engine::doc::appearance_pack::{GlassBoundary, Recipe, STARTER_PACK}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + h.app.session.mark_saved(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(preset.id).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding]; + let mut params = json!({"progressive":true}); + materials::params(&h.app, &mut params).unwrap(); + let wire = ¶ms["raytrace"]["dielectrics"][0]; + assert_eq!(wire["body_name"], "Optics"); + assert_eq!(wire["ior"], recipe.dielectric_ior); + let [r, g, b]: [f64; 3] = serde_json::from_value(wire["absorption_per_mm"].clone()).unwrap(); + let medium = solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + let transmitted = medium.attenuation(recipe.reference_path_mm).unwrap(); + for (actual, expected) in [transmitted.x, transmitted.y, transmitted.z].into_iter().zip(recipe.transmission_linear_rgb) { + assert!((actual - expected).abs() < 1e-12, "the actual optical consumer must reproduce the recipe's linear transmittance"); + } + match recipe.boundary { + GlassBoundary::Closed => { + assert_eq!(wire["boundary"], "closed_mesh"); + assert_eq!(wire["thickness_mm"], 0.0); + } + GlassBoundary::Thin { thickness_mm } => { + assert_eq!(wire["boundary"], "thin_sheet"); + assert_eq!(wire["thickness_mm"], thickness_mm); + } + } + assert!(wire.get("opacity").is_none()); + count += 1; + } + assert_eq!(count, 6); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.materials.enabled = false; + let mut raster = json!({}); + materials::params(&h.app, &mut raster).unwrap(); + assert!(raster.get("raytrace").is_none()); +} + +#[test] +fn gpu_material_identity_requires_explicit_revalidation_and_never_retargets() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.coat_enabled = true; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[20,0,0],"body_name":"Other","operation":"new"})).unwrap(); + let scene = h.app.run("render.scene", json!({})).unwrap(); + let target: materials::Target = + serde_json::from_value(scene["bodies"].as_array().unwrap().iter().find(|body| body["name"] == "Other").unwrap().clone()).unwrap(); + let mut moved = materials::Binding::new(target.clone(), &h.app); + moved.coat_enabled = true; + h.app.render_workspace.view.materials.bindings = vec![moved.clone()]; + h.app.run("browser.visibility", json!({"items":["Optics"],"visible":false})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + assert!(materials::revalidate(&mut h.app, &mut moved).is_err(), "a surviving body with a new ordinal must be selected explicitly"); + assert_eq!(moved.target, target); + let scene = h.app.run("render.scene", json!({})).unwrap(); + assert_eq!(scene["bodies"][0]["name"], "Other"); + assert_ne!(scene["bodies"][0]["ordinal"], target.ordinal); + binding.target.name = "Different body".into(); + assert!(materials::revalidate(&mut h.app, &mut binding).is_err()); + assert_eq!(binding.target.name, "Different body"); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); +} + +#[test] +fn clicked_gpu_glass_recipe_stays_temporary_and_blocks_cpu_rendering() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.session.mark_saved(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.frames(3); + let doc = h.app.session.doc.clone(); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render:material-body-0"}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.material_custom")})).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:starter.glass.amber-tint"}})).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert!(binding.glass_enabled && !binding.coat_enabled && !binding.maps_enabled); + assert_eq!(binding.glass.recipe, Some("starter.glass.amber-tint")); + assert_eq!(binding.target.name, "Optics"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "CPU must not silently ignore active GPU material assignments"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_gpu_material_at_assignment_limit_edits_existing_but_cannot_add_another_body() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1,"body_name":"Optics"})).unwrap(); + h.app.run("solid.pattern.rectangular", json!({"bodies":["Optics"],"dir1":[1,0,0],"count1":129,"spacing1":3})).unwrap(); + let targets: Vec = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"].clone()).unwrap(); + assert_eq!(targets.len(), 129); + h.app.session.mark_saved(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.materials.bindings = targets.iter().skip(1).cloned().map(|target| materials::Binding::new(target, &h.app)).collect(); + h.frames(3); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[1].ordinal)}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let include = h.app.tr("render.material_binding_enable").to_string(); + h.step(&json!({"widget":include})).unwrap(); + assert!(!h.app.render_workspace.view.materials.bindings[0].enabled, "the existing assignment remains editable at the limit"); + assert!(h.app.render_workspace.view.materials.bindings.iter().skip(1).all(|binding| binding.enabled)); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + + // The first scene body has no assignment: selecting it cannot create a 129th entry. + h.step(&json!({"widget":refresh})).unwrap(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[0].ordinal)}})).unwrap(); + h.step(&json!({"widget":add})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + assert!(h.app.render_workspace.view.materials.bindings.iter().all(|binding| binding.target != targets[0])); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn cpu_reflection_controls_preserve_exact_targets_and_engine_bounds() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let reflections = h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap(); + assert_eq!(reflections.bodies.len(), 1); + reflections.max_bounces = 8; + reflections.samples = 64; + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"rough_specular"}])); + assert_eq!(params["raytrace"]["reflections"]["max_bounces"], 8); + assert_eq!(params["raytrace"]["reflections"]["samples"], 64); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 9; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 8; + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 65; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 64; + h.app.session.visibility.hidden_bodies.push("Reflector".into()); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + assert!(h.app.render_workspace.view.raytrace.reflections.is_none()); + assert!(cpu::set_reflection(&mut h.app, "Missing", Some(ReflectionMode::Mirror)).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn cpu_reflection_binding_requires_confirmation_and_never_follows_a_reused_name() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("solid.box", json!({"length":5,"width":5,"height":5,"body_name":"Other"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")) + ); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err(), "confirmation cannot move a binding to a different feature"); + let before = json!(h.app.render_workspace.view.raytrace.reflections); + for mode in [ReflectionMode::Mirror, ReflectionMode::RoughSpecular] { + assert!(cpu::set_reflection(&mut h.app, "Reflector", Some(mode)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before, "a stale row's mode cannot rebind its body"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + } + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + // Isolate document identity: the cloned document has the same bodies, IDs and revision. + let previous_doc = h.app.session.doc.clone(); + let previous_revision = h.app.session.revision; + h.app.session = Session::new((*previous_doc).clone()); + h.app.session.revision = previous_revision; + assert!(!Arc::ptr_eq(&previous_doc, &h.app.session.doc)); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); +} + +#[test] +fn cpu_interactive_reflection_binding_accepts_appearance_and_render_intent_without_qualifying_final() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let world = h.app.session.world_state(); + let mesh = world.body("Reflector").unwrap().cached_mesh().unwrap(); + let document = h.app.session.doc.clone(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Reflector"],"color":"#123456"})).unwrap(); + assert!(!Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(Arc::ptr_eq(&mesh, &h.app.session.world_state().body("Reflector").unwrap().cached_mesh().unwrap())); + h.app.run("render.settings.set", json!({"name":"Interactive target proof","set":{"width":800,"height":600}})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-interactive-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.25; + h.app.render_workspace.view.cpu.intensity = 2.0; + let before = json!(h.app.render_workspace.view.raytrace.reflections); + let mut interactive = json!({}); + cpu::params_interactive(&h.app, &mut interactive).unwrap(); + assert_eq!(interactive["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"mirror"}])); + assert_eq!(interactive["raytrace"]["exposure_ev"], 1.5); + assert_eq!(interactive["environment"]["rotation_radians"], 0.25); + assert_eq!(interactive["environment"]["expected_sha256"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before); + assert!( + cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")), + "Interactive refresh cannot qualify final Check/Start" + ); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).is_err(), + "mode changes still require explicit confirmation" + ); +} + +#[test] +fn cpu_interactive_binding_keeps_cold_meshes_cold_and_refuses_another_world_until_confirmation() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + let retained = Arc::strong_count(&world); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none(), "request lowering must not tessellate"); + assert_eq!(Arc::strong_count(&world), retained, "the binding must not retain the evaluated world"); + h.app.session.execute("appearance.assign", &json!({"bodies":["Reflector"],"color":"#654321"})).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + h.app.session.execute("solid.box", &json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_interactive_binding_refuses_reused_names_and_same_revision_in_a_new_document() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let uid = h.app.session.uid; + h.app.session = Session::new((*document).clone()); + h.app.session.revision = revision; + assert_ne!(h.app.session.uid, uid); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); +} + +#[test] +fn cpu_interactive_binding_refuses_moved_occurrences_and_hidden_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.run("component.create", json!({"name":"Part","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let name = world.bodies[0].name.clone(); + let mesh = world.bodies[0].mesh(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let moved = h.app.session.world_state(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(!Arc::ptr_eq(&mesh, &moved.bodies[0].mesh())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "same creator and name cannot certify a moved instance"); + cpu::revalidate(&mut h.app, &name).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + h.app.session.visibility.hidden_bodies.push(name); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); +} + +#[test] +fn cpu_interactive_binding_refuses_deleted_then_recreated_equal_looking_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let feature = world.body("Reflector").unwrap().feature; + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("timeline.delete", json!({"feature":feature.to_string()})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + assert!(h.app.session.world_state().body("Reflector").is_some(), "the recreated case must actually reuse the selected name"); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "identical names/dimensions cannot certify recreated geometry"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_environment_controls_keep_wire_schemas_separate_without_reading_files() { + let mut h = Harness::new(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + let mut hdr = json!({}); + cpu::params(&h.app, &mut hdr).unwrap(); + assert_eq!( + hdr["environment"], + json!({"path":"not-opened-by-ui.hdr","expected_sha256":h.app.render_workspace.view.cpu.hdr.resource().unwrap(),"rotation_radians":std::f64::consts::FRAC_PI_2,"intensity":2.0,"samples":64}) + ); + assert!(hdr["raytrace"].get("environment").is_none()); + for gpu_key in ["progressive", "tone_map", "denoise", "lighting", "lens"] { + assert!(hdr.get(gpu_key).is_none()); + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.2, 0.4, 0.8]; + let mut constant = json!({}); + cpu::params(&h.app, &mut constant).unwrap(); + assert!(constant.get("environment").is_none()); + assert_eq!(constant["raytrace"]["environment"], json!({"color":[0.2,0.4,0.8],"intensity":2.0})); + assert!(h.app.render_workspace.view.raytrace.environment.is_none(), "request building must not mutate the editable base"); + h.app.render_workspace.view.cpu.color[0] = f64::NAN; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.samples = 3; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.samples = 16; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("bad\npath.hdr"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + let mut none = json!({}); + cpu::params(&h.app, &mut none).unwrap(); + assert!(none.get("environment").is_none()); + assert!(none["raytrace"].get("environment").is_none()); +} + +#[test] +fn cpu_light_controls_preserve_hidden_spot_fields_and_validate_runtime_bounds() { + use solidcraft_engine::render::job::{DirectionalLightOptions, PunctualLightOptions, SpotConeOptions}; + let mut h = Harness::new(); + 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.raytrace.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 100.0], + color: [1.0, 0.5, 0.25], + intensity: 4.0, + reference_distance_mm: 100.0, + minimum_distance_mm: 0.01, + cone: None, + }]); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["lights"][0]["intensity"], 2.0); + assert_eq!(params["raytrace"]["punctual_lights"][0]["reference_distance_mm"], 100.0); + assert!(params.get("lighting").is_none(), "CPU must not emit GPU studio lighting"); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0; 3]; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0, 0.0, 1.0]; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 101.0; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 0.01; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].cone = + Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.1, outer_half_angle_radians: 0.2 }); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!( + params["raytrace"]["punctual_lights"][0]["cone"], + json!(h.app.render_workspace.view.raytrace.punctual_lights.as_ref().unwrap()[0].cone) + ); +} + +#[test] +fn delayed_cpu_hdr_picker_cannot_write_into_another_document_or_revision() { + use crate::picker_test_support::{Slot, open}; + for other_document in [false, true] { + let mut h = Harness::new(); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "original.hdr".into() }; + hdr::pick(&mut h.app, hdr::Target::Cpu); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy()); + if other_document { + h.app.session = Session::default(); + } else { + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5})).unwrap(); + } + *slot.borrow_mut() = Some(Some("late.hdr".into())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.cpu.hdr, hdr::Input::FilePending { path: "original.hdr".into() }); + } +} + +#[test] +fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host() { + use solidcraft_engine::doc::render_settings::{GpuJob, RenderJob, SkyEnvironment}; + use solidcraft_engine::render::job::{AreaLight, AreaLights, StudioLighting, Sun, ThinLens, ToneMap}; + use solidcraft_engine::render::lighting::environment::SkyGradient; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.frames(3); + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + h.app.cam.fov = 0.7; + h.app.ui.perspective = true; + // The positive UI fixture uses the admitted document boundary. Coordinates + // beyond it must still refuse before a setup that cannot reopen is created. + for x in [-2e9, 2e9, 1e9_f64.next_up()] { + assert!( + AreaLights::new(&[AreaLight { center: [x, 0.0, 100.0], u: [2.0, 0.0, 0.0], v: [0.0, -3.0, 0.0], radiance: [3.0, 5.0, 7.0] }]).is_err() + ); + } + let expected = RenderSetup { + camera: h.app.cam, + exposure_ev: 1.25, + width: 48, + height: 32, + job: Some(RenderJob::GpuPath { + transparent_background: true, + options: Box::new(GpuJob { + aging: Default::default(), + nested_media: true, + volume: Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }), + adaptive: Some(solidcraft_engine::render::job::adaptive::AdaptiveSampling { + pilot_samples: 16, + min_samples: 16, + relative_error: 0.1, + absolute_error: 0.003, + coverage_error: 0.02, + }), + transmission_samples: 4, + finishing: Default::default(), + backdrop: None, + linear_exr: false, + samples: 37, + max_depth: 11, + seed: 1977, + tone_map: ToneMap::AcesFitted, + denoise: true, + lens: Some(ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 123.0 }), + lighting: Some(StudioLighting { + environment: [0.25, 0.5, 0.75], + sun: Some(Sun { direction: [2.0, 3.0, 4.0], angular_radius_rad: 0.0123456789, radiance: [11.0, 22.0, 33.0] }), + area_lights: AreaLights::new(&[AreaLight { + center: [1e9, 0.0, 100.0], + u: [2.0, 0.0, 0.0], + v: [0.0, -3.0, 0.0], + radiance: [3.0, 5.0, 7.0], + }]) + .unwrap(), + }), + environment: Some(SkyEnvironment::Sky { + gradient: SkyGradient { zenith: [0.3, 0.4, 0.5], horizon: [0.6, 0.7, 0.8], ground: [0.1, 0.2, 0.3] }, + rotation_rad: std::f64::consts::PI, + intensity: 1.75, + }), + hdr: None, + }), + }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"GPU saved","set":expected})).unwrap(); + h.app.render_workspace.view.name = "GPU saved".into(); + setups::load(&mut h.app); + let completed = h.app.render_workspace.view.completed; + let result_camera = h.app.render_workspace.view.result_camera; + h.frames(3); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(image_params(&h.app).is_err(), "offline editing must not claim an executable GPU"); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.step(&json!({"click":{"handle":"render:setup-name"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"GPU copy"})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "GPU copy"); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "typing Save As must not reset the settings"); + assert!(h.app.render_workspace.view.dirty); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["GPU copy"], expected); + h.app.render_workspace.view.seed = 8; + h.app.render_workspace.view.studio.ambient[1] = 0.125; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.render_workspace.view.name = "Raster saved".into(); + setups::save(&mut h.app).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:setups"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:setup:GPU copy"}})).unwrap(); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.completed, completed); + assert_eq!(h.app.render_workspace.view.result_camera, result_camera); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the boundary setup must reopen from JSON"); + let native = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&native).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the native container keeps exact numeric intent"); +} + +#[test] +fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":4,"shadows":false, + "lights":[{"direction":[2.0,-4.0,8.0],"color":[0.2,0.4,0.6],"intensity":3.0}], + "punctual_lights":[{"position_mm":[10.0,20.0,30.0],"color":[1.0,0.5,0.25],"intensity":4.0, + "reference_distance_mm":100.0,"minimum_distance_mm":0.01, + "cone":{"emitted_axis":[0.0,0.0,-2.0],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.3}}], + "area_lights":[{"center_mm":[0.0,0.0,100.0],"edge_u_mm":[20.0,0.0,0.0],"edge_v_mm":[0.0,-30.0,0.0],"color":[0.3,0.5,0.7],"intensity":5.0}], + "area_samples":16,"seed":9123,"environment":{"color":[0.0,0.0,0.0],"intensity":2.0} + })) + .unwrap(); + let mut expected = RenderSetup { camera: h.app.cam, exposure_ev: 1.5, job: Some(RenderJob::CpuRaytrace { options }), ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + h.app.render_workspace.view.name = "CPU numeric".into(); + setups::load(&mut h.app); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"directional:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0, "the UI has one exposure authority"); + h.app.render_workspace.view.draft.background = [2, 4, 8]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + expected.background = [2, 4, 8]; + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(json!(expected)["job"]["options"].get("exposure_ev").is_none()); + for value in [json!({}), json!({"lights":[],"punctual_lights":[],"area_lights":[],"environment":{"color":[0.0,0.0,0.0],"intensity":0.0}})] { + let options: CpuJob = serde_json::from_value(value).unwrap(); + expected.job = Some(RenderJob::CpuRaytrace { options }); + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + } +} + +#[test] +fn cpu_progressive_controls_resize_only_on_request_and_save_reload_without_a_host() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.primary_samples = 16; + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 1024; + h.frames(3); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-progressive"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 1); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions::default())); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: u32::MAX }); + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.name = "Progressive CPU".into(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(image_request(&h.app).is_err()); + assert!(setups::save(&mut h.app).is_err()); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let resize = format!("{} 512 × 512", h.app.tr("render.image_use_largest")); + assert!(h.widget(&resize).is_some(), "the proposed dimensions must be visible before accepting them"); + h.step(&json!({"widget":resize})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (512, 512)); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert!(image_request(&h.app).unwrap().get("progressive").is_none(), "CPU sampling must not select the GPU executor"); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Progressive CPU"], expected); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-fixed"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + h.app.render_workspace.view.name = "Progressive CPU copy".into(); + setups::save(&mut h.app).unwrap(); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 1.25); +} + +#[test] +fn cpu_progressive_setup_preserves_hidden_values_empty_lists_and_one_exposure() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.app.session.set_render_job_host(None).unwrap(); + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":1,"progressive":{"samples_per_pixel":7,"seed":321},"preset":null, + "lights":[],"punctual_lights":null,"area_lights":[],"area_samples":16,"seed":9123, + "shadows":false,"environment":{"color":[0.0,0.0,0.0],"intensity":0.0} + })) + .unwrap(); + let expected = RenderSetup { + camera: h.app.cam, + width: 32, + height: 16, + exposure_ev: -1.5, + job: Some(RenderJob::CpuRaytrace { options }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"Progressive hidden","set":expected})).unwrap(); + h.app.render_workspace.view.name = "Progressive hidden".into(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["method"], "gpu_path"); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().seed = 654; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + let undo = h.app.session.undo.len(); + setups::save(&mut h.app).unwrap(); + assert_eq!(h.app.session.undo.len(), undo, "a no-op Save must preserve all nonedited intent"); +} + +#[test] +fn setup_save_refuses_nonportable_state_atomically_and_tracks_invalid_legacy_edits() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Target"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + setups::load(&mut h.app); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + setups::save(&mut h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "must-not-be-read.hdr".into() }; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.hdr_inspect_required"))); + h.app.render_workspace.view.studio.environment = studio::Environment::None; + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.render_workspace.view.materials.enabled = false; + assert!(setups::save(&mut h.app).is_err(), "disabled assignments must not be silently lost either"); + h.app.render_workspace.view.materials.bindings.clear(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.run("render.settings.set", json!({"name":"Legacy","set":{"job":null,"environment_rotation":0.25,"environment_intensity":2.0}})).unwrap(); + h.app.render_workspace.view.name = "Legacy".into(); + setups::load(&mut h.app); + assert!(!h.app.render_workspace.view.dirty); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.draft.background = [1, 3, 5]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "invalid saved intent still needs complete dirty tracking"); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.setup_legacy_environment"))); + assert_eq!(h.app.render_workspace.view.draft.environment_rotation, 0.25); + assert_eq!(h.app.render_workspace.view.draft.environment_intensity, 2.0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +fn original_hdr_bytes(value: u8, declared_primaries: bool) -> Vec { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n".to_vec(); + if declared_primaries { + bytes.extend_from_slice(b"PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"); + } + bytes.extend_from_slice(b"\n-Y 1 +X 2\n"); + bytes.extend_from_slice(&[value, 128, 128, 129, 128, value, 128, 129]); + bytes +} + +/// A verified selector for pure request tests. No file exists or is read by the builder. +fn captured_hdr_input(path: &str) -> hdr::Input { + let bytes = original_hdr_bytes(128, true); + hdr::Input::FileCaptured { + path: path.into(), + metadata: hdr::Metadata { + sha256: solidcraft_engine::doc::render_resources::HdrId::of(&bytes), + width: 2, + height: 1, + encoded_bytes: bytes.len() as u64, + primaries: Some(solidcraft_engine::doc::render_resources::SRGB_D65_PRIMARIES), + }, + } +} + +#[test] +fn hdr_ui_save_embeds_once_without_a_host_and_reload_never_reopens_the_source_path() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"HDR target","length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + let path = h.dir.join("original-embedded.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + let resource = solidcraft_engine::doc::render_resources::HdrId::of(&bytes); + let save = h.app.tr("render.save_setup").to_string(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.render_workspace.view.name = "HDR GPU".into(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.rotation_rad = 1234.567890123; + h.app.render_workspace.view.studio.intensity = 1.75; + h.app.render_workspace.view.samples = 37; + let before = (h.app.session.revision, h.app.session.undo.len()); + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert!(h.app.session.doc.render.resources.is_empty()); + let unsaved = image_request(&h.app).unwrap(); + assert_eq!(unsaved["environment"]["expected_sha256"], json!(resource)); + h.frames(3); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), before.1 + 1); + assert_eq!(h.app.render_workspace.view.studio.hdr, hdr::Input::EmbeddedResource { resource }); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + let gpu = h.app.session.doc.render.setups.get("HDR GPU").unwrap().clone(); + assert!(matches!(&gpu.job, Some(RenderJob::GpuPath { options, .. }) if options.hdr.unwrap().resource == resource && options.samples == 37)); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":gpu})); + assert!(!h.app.render_workspace.view.dirty); + + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "HDR CPU".into(); + h.app.render_workspace.view.raytrace.progressive = Some(solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: 7, seed: 84 }); + h.app.render_workspace.view.draft.exposure_ev = 1.75; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.rotation_rad = -1234.567890123; + h.app.render_workspace.view.cpu.intensity = 2.5; + h.app.render_workspace.view.cpu.samples = 64; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + h.frames(2); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1, "both setups share one source payload"); + assert_eq!(h.app.session.doc.render.resources.total_bytes(), bytes.len()); + let cpu = h.app.session.doc.render.setups.get("HDR CPU").unwrap().clone(); + assert!(matches!(&cpu.job, Some(RenderJob::CpuRaytrace { options }) + if options.hdr.unwrap().samples == 64 && options.progressive.unwrap().samples_per_pixel == 7 && options.progressive.unwrap().seed == 84)); + let encoded = h.app.session.doc.to_json(); + assert!(!encoded.contains("original-embedded.hdr"), "the document never stores the source path"); + std::fs::remove_file(&path).unwrap(); + + for (name, expected, target) in [("HDR GPU", gpu, hdr::Target::Gpu), ("HDR CPU", cpu, hdr::Target::Cpu)] { + let loaded = solidcraft_engine::doc::Document::from_json(&encoded).unwrap(); + h.app.session = Session::new(loaded); + h.app.render_workspace.view.name = name.into(); + setups::load(&mut h.app); + let camera = expected.camera; + h.app.cam = camera; + assert_eq!(hdr::input(&h.app, target), &hdr::Input::EmbeddedResource { resource }); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + let before = (h.app.session.revision, h.app.session.undo.len()); + let section = if target == hdr::Target::Cpu { "render.cpu_environment" } else { "render.studio_environment" }; + h.frames(2); + if target == hdr::Target::Gpu { + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr("render.image_advanced"))}})).unwrap(); + } + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr(section))}})).unwrap(); + h.frames(2); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "displaying degrees must preserve saved radians"); + setups::save(&mut h.app).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn changed_hdr_bytes_reject_save_atomically_and_check_start_keep_the_expected_digest() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Pinned HDR".into(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + let path = h.dir.join("changing.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let input = h.app.render_workspace.view.cpu.hdr.clone(); + let request = image_request(&h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let draft = h.app.render_workspace.view.draft.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), before); + assert_eq!(h.app.render_workspace.view.cpu.hdr, input); + assert_eq!(h.app.render_workspace.view.draft, draft); + assert_eq!(image_request(&h.app).unwrap(), request, "both buttons keep the verified digest, never silently accept new bytes"); + assert!(h.app.session.doc.render.resources.is_empty()); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert_ne!(h.app.render_workspace.view.cpu.hdr.resource(), input.resource()); + setups::save(&mut h.app).unwrap(); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + assert_eq!(h.app.session.doc.render.resources.len(), 1); +} + +#[test] +fn hdr_picker_cancel_and_late_setup_method_or_input_answers_preserve_the_selection() { + use crate::picker_test_support::{Slot, open}; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + for change in ["cancel", "setup", "method", "input"] { + let mut h = Harness::new(); + h.app.render_workspace.view.method = if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("original.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("original.hdr"); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + hdr::pick(&mut h.app, target); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + match change { + "setup" => h.app.render_workspace.view.name = "another setup".into(), + "method" => h.app.render_workspace.view.method = ImageMethod::Raster, + "input" => { + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("newer.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("newer.hdr"); + } + _ => {} + } + let before = hdr::input(&h.app, target).clone(); + let doc = h.app.session.doc.clone(); + let status = h.app.status.clone(); + *slot.borrow_mut() = Some(if change == "cancel" { None } else { Some("never-read-late.hdr".into()) }); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(hdr::input(&h.app, target), &before, "{target:?}: {change}"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status, status, "the stale path must be discarded before trying to inspect it"); + } + } +} + +#[test] +fn embedded_hdr_runtime_requests_preserve_temporary_bindings_without_serializing_them() { + use solidcraft_engine::render::job::ReflectionMode; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"Target","length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + let path = h.dir.join("bindings.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + setups::save(&mut h.app).unwrap(); + let resource = hdr::input(&h.app, target).resource().unwrap(); + std::fs::remove_file(&path).unwrap(); + if target == hdr::Target::Cpu { + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + } else { + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + // Even disabled, this assignment must not be lost on Save. It still + // selects the runtime path and exercises the embedded HDR selector. + h.app.render_workspace.view.materials.enabled = false; + } + let params = image_request(&h.app).unwrap(); + assert_eq!(params["environment"]["resource"], json!(resource)); + assert!(params["environment"].get("path").is_none()); + assert!(params["environment"].get("expected_sha256").is_none()); + if target == hdr::Target::Cpu { + assert!(params["environment"].get("kind").is_none()); + assert_eq!(params["raytrace"]["reflections"]["bodies"][0]["body"], "Target"); + } else { + assert_eq!(params["environment"]["kind"], "embedded_hdr"); + } + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_request(&h.app).unwrap(), params); + } +} + +#[test] +fn cpu_resource_profile_edits_preserve_resolution_samples_and_saved_intent() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Studio output".into(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Studio; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 82 }); + h.frames(3); + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + + h.step(&json!({"click":{"handle":"render.cpu_budget_compact"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (3840, 2160)); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 128); + assert!(setups::snapshot(&h.app).is_err()); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); +} + +#[test] +fn large_image_display_uses_captured_profile_and_keeps_export_pixels_unchanged() { + use solidcraft_engine::render::job::{CpuBudget, ImageRequest, RaytraceOptions}; + let request = 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(RaytraceOptions { budget: CpuBudget::Studio, ..Default::default() }), + camera: Camera::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + environment: None, + textures: None, + }; + let limits = captured_image_limits(&request); + assert_eq!(limits, CpuBudget::Studio.image_limits(false)); + assert_eq!(display_dimensions(7680, 4320, 4096).unwrap(), (4096, 2304)); + assert_eq!(display_dimensions(1920, 1080, 4096).unwrap(), (1920, 1080)); + assert!(display_dimensions(u32::MAX, 1, 0).is_err()); + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(8200, 2, image::Rgba([42, 88, 123, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let encoded = png.into_inner(); + let before = encoded.clone(); + assert!(decode_image(&encoded, 8200, 2).is_err(), "legacy default remains compact"); + let display = decode_render_image(&encoded, 8200, 2, CpuBudget::Workstation.image_limits(false), 1024).unwrap(); + assert!(display.size[0] <= 1024 && display.size[1] >= 1); + assert_eq!(encoded, before, "the retained image is not rewritten for its display cache"); + assert!(decode_render_image(&encoded, 8199, 2, CpuBudget::Workstation.image_limits(false), 1024).is_err()); +} + +#[test] +fn setup_actions_and_return_design_stay_visible_with_long_render_controls() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.frames(3); + for key in ["render.save_setup", "render.reload_settings", "render.return_design"] { + let label = h.app.tr(key).to_string(); + assert!(h.widget(&label).is_some(), "sticky action {key}"); + } + h.step(&json!({"widget":h.app.tr("render.return_design")})).unwrap(); + assert!(!active(&h.app)); +} + +#[test] +fn dirty_indication_preserves_reload_and_resource_picker_hit_targets() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + h.frames(3); + let reload = h.app.tr("render.reload_settings").to_string(); + let clean_reload = h.widget(&reload).unwrap(); + let clean_picker = crate::scenario::rect_of("render:cpu-budget").unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.frames(3); + assert_eq!(h.widget(&reload).unwrap(), clean_reload, "dirty text must not move Reload"); + assert_eq!(crate::scenario::rect_of("render:cpu-budget").unwrap(), clean_picker, "dirty text must not move the CPU resource picker"); + h.step(&json!({"widget":reload})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert!(!h.app.render_workspace.view.dirty); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 0.0); +} + +#[test] +fn product_preview_exact_payload_preserves_mixed_surfaces_and_refuses_overflow() { + let mut session = Session::default(); + for (name, x) in [("Paint", 0), ("Legacy", 20), ("Glass", 40)] { + session.execute("solid.box", &json!({"base":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + session + .execute("appearance.assign", &json!({"bodies":["Paint"],"color":"#c07030","pbr":{"metallic":0,"roughness":0.4,"dielectric_ior":1.5}})) + .unwrap(); + session.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let original = session.doc.to_json(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + let (_, gpu) = gpu_scene(&scene).unwrap(); + assert_eq!((plan.pbr, plan.tris, plan.glass), (gpu.pbr.len(), gpu.tris.len(), gpu.glass.len())); + assert!(plan.pbr > 0 && plan.tris > 0 && plan.glass > 0); + assert_eq!(plan.source_triangles, scene.meshes.iter().map(|b| b.mesh.triangles.len()).sum::()); + assert!(preview_upload_plan(&scene, plan.bytes().unwrap() - 1).is_err()); + assert!(PreviewUploadPlan::default().add(true, false, usize::MAX, MAX_GEOMETRY_BYTES).is_err()); + assert_eq!(session.doc.to_json(), original); + let mut invalid = scene.clone(); + let source = invalid.meshes[0].mesh.clone(); + Arc::make_mut(&mut invalid.meshes[0].mesh).triangles[0][0] = u32::MAX; + assert!(gpu_scene(&invalid).is_err()); + assert!(gpu_scene(&scene).is_ok()); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &source)); +} + +#[cfg(all(not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn full_detail_preview_source_can_exceed_legacy_128_mib_without_mesh_reduction() { + use solidcraft_engine::geom::{Mesh, Vec3}; + use solidcraft_engine::render::{ProductMesh, surface::OpaqueSurface}; + // One immutable original triangle repeated in the index list; this tests + // payload admission only. Actual SELENE upload is separate native evidence. + let count = (128 * 1024 * 1024) / (3 * crate::gpu::PBR_SIZE) + 1; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]; count], + ..Default::default() + }); + let body = ProductMesh { + name: "Original admission fixture".into(), + mesh: mesh.clone(), + color: [200, 100, 50], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.4, 0.2, 0.1), 0.0, 0.4, 1.5).unwrap()), + transmission: None, + faces: Vec::new(), + }; + let scene = ProductScene { meshes: vec![body], bounds: mesh.bounds() }; + assert!(preview_upload_plan(&scene, 128 * 1024 * 1024).is_err()); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + assert_eq!(plan.source_triangles, count); + assert_eq!(plan.bytes().unwrap(), count * 3 * crate::gpu::PBR_SIZE); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &mesh)); + let mut maximum = PreviewUploadPlan::default(); + assert!(maximum.add(true, false, MAX_GEOMETRY_BYTES / (3 * crate::gpu::PBR_SIZE) + 1, MAX_GEOMETRY_BYTES).is_err()); +} + +#[test] +fn refused_product_capture_is_cached_until_identity_changes_or_explicit_retry() { + let mut h = Harness::new(); + let calls = std::cell::Cell::new(0); + let signature = (7, 123, 99, MAX_GEOMETRY_BYTES as u64); + for _ in 0..8 { + assert_eq!( + h.app + .render_workspace + .prepare_preview(signature, || { + calls.set(calls.get() + 1); + Err("original bounded refusal".into()) + }) + .unwrap_err(), + "original bounded refusal" + ); + } + assert_eq!(calls.get(), 1, "same refused source is not rebuilt every frame"); + assert!(h.app.render_workspace.scene.is_none() && h.app.render_workspace.key.is_none()); + assert!(h.app.render_workspace.slot.lock().unwrap().is_none()); + assert!( + h.app + .render_workspace + .prepare_preview((8, 123, 99, MAX_GEOMETRY_BYTES as u64), || { + calls.set(calls.get() + 1); + Err("new revision".into()) + }) + .is_err() + ); + assert_eq!(calls.get(), 2); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.scene_signature.is_none() && h.app.render_workspace.scene_error.is_none()); + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + h.app.render_workspace.prepare_preview(signature, || solidcraft_engine::product_scene::extract(&session).map_err(|e| e.to_string())).unwrap(); + assert!(h.app.render_workspace.scene_error.is_none()); + assert!(h.app.render_workspace.preview_upload_bytes.unwrap() > 0); + assert!(h.app.render_workspace.key.is_some() && h.app.render_workspace.scene.is_some()); +} + +#[test] +fn product_preview_error_uses_shared_wrapped_surface_and_explicit_retry_target() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":800})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rect = egui::Rect::from_min_size(egui::pos2(260.0, 200.0), egui::vec2(550.0, 360.0)); + let message = "The original captured product geometry exceeds its bounded preview admission. The renderer must preserve all exact body identities and cannot silently simplify or drop geometry to paint this view."; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), ..Default::default() }, + |ui| preview_error(&mut h.app, ui, rect, message), + ); + output.textures_delta.clear(); + let note = crate::scenario::rect_of("dialog:report:render.preview_failure").unwrap(); + let retry = crate::scenario::rect_of("render:preview-retry").unwrap(); + assert!(rect.contains_rect(note) && rect.contains_rect(retry)); + assert!(note.height() > Tokens::get().font_body, "the detailed failure wraps instead of escaping the viewport"); + assert!(crate::theme::contrast_ratio(Tokens::get().form_error, Tokens::get().form_error_fill) >= 3.0); +} + +#[test] +fn finishing_backdrop_and_raw_retention_save_reload_without_a_gpu_or_hidden_transport_edits() { + use solidcraft_engine::render::job::finishing::{Backdrop, BackdropMode, Finishing}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.render_workspace.view.name = "Linear studio".into(); + h.app.render_workspace.view.studio.finishing = + Finishing { rgb_gain: [1.3, 0.8, 0.9], saturation: 0.4, contrast: 1.2, vignette: 0.3, ..Default::default() }; + h.app.render_workspace.view.studio.backdrop_enabled = true; + h.app.render_workspace.view.studio.backdrop = Backdrop { mode: BackdropMode::Radial, center: [0.25, 0.7], ..Default::default() }; + h.app.render_workspace.view.studio.linear_exr = true; + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.studio = studio::View::default(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(!studio::linear_export_available(&h.app)); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["linear_exr"], true); + assert_eq!(request["settings"]["job"]["options"]["finishing"]["rgb_gain"], json!([1.3, 0.8, 0.9])); + assert!(image_params(&h.app).is_err(), "offline editing is not a claim of executable GPU capabilities"); + h.app.render_workspace.view.transparent = true; + assert!(setups::snapshot(&h.app).is_err(), "gradient cannot silently disappear behind alpha mode"); + h.app.render_workspace.view.transparent = false; + let before = h.app.session.doc.to_json(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:post-reset"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.studio.finishing, Finishing::default()); + assert!(h.app.render_workspace.view.studio.linear_exr); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + assert!(h.app.render_workspace.view.dirty); + assert_ne!(h.app.session.doc.to_json(), before, "Effects saves its job patch through the shared editor"); + let reset = setups::snapshot(&h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), reset); +} + +#[test] +fn missing_linear_master_is_never_reconstructed_from_a_finished_png() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + let id = completed_preview(&mut h, [21, 37, 55]); + let bytes = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.completed = Some(id); + h.app.render_workspace.view.studio.export_exr = true; + assert!(!studio::linear_export_available(&h.app)); + let temp = std::env::temp_dir().join(format!("solidcraft-missing-linear-{}.exr", std::process::id())); + assert!(h.app.session.execute("render.export", &json!({"job":id,"path":temp,"format":"exr"})).is_err()); + assert!(!temp.exists()); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), bytes); +} + +#[test] +fn render_workspace_stage_commands_keep_registered_actions_without_a_ribbon() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + assert!(crate::workspace::visible_tabs(&h.app).is_empty()); + for command in solidcraft_engine::command_specs() + .into_iter() + .filter(|c| c.id.starts_with("render.") || c.tab.starts_with("RENDER") || c.id == "view.shots_strip") + { + assert!(solidcraft_engine::find_command(command.id).is_some()); + assert!(crate::workspace::destination(command).is_none(), "{} has a ribbon destination", command.id); + } + for tab in ["RENDER", "RENDER APPEARANCE", "RENDER SCENE", "RENDER CAMERA"] { + assert!(crate::workspace::panels(tab).is_empty()); + } + h.frames(3); + assert!(crate::scenario::rect_of("ribbon:card").is_none()); + assert!(crate::scenario::rect_of("tab:RENDER").is_none()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); +} + +#[test] +fn render_workspace_stage_chips_dispatch_without_mutations_and_remember_each_document() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for stage in Stage::ALL { + h.frames(3); + h.step(&json!({"click":{"handle":format!("render:stage:{}",stage.key())}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.stage, stage); + assert_eq!(h.app.render_workspace.view.inspector.page, stage.page()); + assert_eq!(crate::scenario::rect_of("render:pick").is_some(), stage == Stage::Look); + assert_eq!(crate::scenario::rect_of("render:preview_note").is_some(), stage == Stage::Look); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + // Registered editor navigation remains available independently of the stage. + for command in ["render.status", "render.backends"] { + h.app.start(command); + h.frames(2); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Diagnostics); + } + } + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Frame); + crate::documents::switch(&mut h.app, 1); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); +} + +#[test] +fn render_workspace_stage_shell_degrades_without_overlap_at_small_window_sizes() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.ui.layout = mode; + for (width, height) in [ + (1440, 900), + (1400, 900), + (1100, 700), + (900, 700), + (800, 600), + (700, 600), + (640, 480), + (320, 240), + (240, 160), + (120, 80), + (32, 32), + (1, 1), + ] { + h.call("ui.resize", json!({"width":width,"height":height})); + for stage in Stage::ALL { + h.app.run("view.render_stage", json!({"stage":stage.key()})).unwrap(); + h.frames(3); + let bar = crate::scenario::rect_of("render:stage_bar").unwrap(); + let workspace = crate::scenario::rect_of("ribbon:workspace").unwrap(); + assert!(bar.is_finite() && workspace.is_finite()); + assert_eq!(bar.top(), workspace.top()); + assert_eq!(bar.height(), workspace.height()); + assert!(!bar.intersect(workspace).is_positive()); + if width >= 1100 { + assert_eq!(bar.height(), 88.0); + assert_eq!(workspace.width(), 104.0); + assert_eq!(bar.left() - workspace.right(), 8.0); + let header = crate::scenario::rect_of("render:stage_header").unwrap(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert_eq!(header.height(), 36.0); + assert_eq!(tools.height(), 52.0); + assert_eq!(header.bottom(), tools.top()); + assert_eq!(header.top(), bar.top()); + assert_eq!(tools.bottom(), bar.bottom()); + } + let docks: Vec<_> = + ["render:browser", "render:inspector"].iter().filter_map(|id| h.app.shell.workspace_panels.get(id).map(|(r, _)| *r)).collect(); + if let [browser, inspector] = docks.as_slice() { + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!(browser.bottom() < inspector.bottom()); + assert!(!browser.intersect(*inspector).is_positive()); + if width >= 800 { + let compact = crate::render_ui::compact(&h.app, width as f32); + assert_eq!(browser.width(), if compact { crate::frame::DIALOG_MIN_W } else { 266.0 }); + assert_eq!(inspector.width(), if compact { crate::frame::DIALOG_MIN_W } else { 305.0 }); + assert_eq!(browser.top() - bar.bottom(), 8.0); + let (strip, _) = h.app.shell.workspace_panels.get("render:shots_strip").unwrap(); + let library = h.app.shell.workspace_panels["render:appearances"].0; + assert_eq!(strip.top() - library.bottom(), 8.0); + assert_eq!(library.top() - browser.bottom(), 8.0); + assert_eq!(strip.height(), 48.0); + } + } + if (640..800).contains(&width) { + assert!(crate::scenario::rect_of("render:browser:show").is_some()); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + if width >= 700 { + for dock in &docks { + assert!(!dock.x_range().contains(h.app.viewport.rect.unwrap().center().x), "{width}: {dock:?}"); + } + } + let mut docks = docks; + if let Some((panel, _)) = h.app.shell.workspace_panels.get("render:appearances") { + for dock in &docks { + assert!(!panel.intersect(*dock).is_positive()); + } + docks.push(*panel); + } + for dock in docks { + assert!(!dock.intersect(bar).is_positive(), "{width}×{height}: {dock:?} {bar:?}"); + if let Some((strip, _)) = h.app.shell.workspace_panels.get("render:shots_strip") { + assert!(!dock.intersect(*strip).is_positive(), "{width}×{height}: {dock:?} {strip:?}"); + } + } + } + } + } +} + +#[test] +fn render_workspace_focus_restores_docks_without_design_history_or_camera_changes() { + for (side, folded, shots) in [("left", false, true), ("right", true, false)] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 350.0; + h.app.preferences.render_inspector_width = 390.0; + h.app.preferences.render_shots_strip = shots; + h.app.preferences.browser_collapsed = folded; + h.app.shell.render_browser_open = folded; + h.frames(3); + let dock_preferences = h.app.prefs(); + let docks = h.app.shell.workspace_panels.clone(); + let camera = (h.app.cam, h.app.session.camera); + let document = h.app.session.doc.clone(); + let state = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let before = h.app.viewport.layout.as_ref().unwrap().content; + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + assert!(crate::render_ui::focused(&h.app)); + crate::shell::register_panel(&mut h.app, "render:stage_panel", Some(before), Some(crate::ui_kit::Edge::Left)); + assert!(!h.app.shell.workspace_panels.contains_key("render:stage_panel")); + for id in ["render:browser", "render:appearances", "render:inspector", "render:shots_strip", "render:shots:show"] { + assert!(!h.app.shell.workspace_panels.contains_key(id)); + assert!(crate::scenario::rect_of(id).is_none()); + } + for id in ["render:focus:exit", "render:stage_bar", "ribbon:workspace"] { + assert!(crate::scenario::rect_of(id).is_some(), "{id}"); + } + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(layout.content.width() > before.width()); + assert!(layout.axis_view.is_positive() && layout.navigation.is_positive()); + assert_eq!(h.app.prefs(), dock_preferences); + h.step(&json!({"click":{"handle":"render:focus:exit"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.render_focus); + assert_eq!(h.app.shell.workspace_panels.len(), docks.len()); + for (id, (rect, edge)) in docks { + let (restored_rect, restored_edge) = h.app.shell.workspace_panels.get(id).unwrap(); + assert_eq!(*restored_rect, rect); + assert_eq!(restored_edge.as_ref().map(std::mem::discriminant), edge.as_ref().map(std::mem::discriminant)); + } + assert_eq!(h.app.prefs(), dock_preferences); + assert_eq!(h.app.preferences.browser_collapsed, folded); + assert_eq!(h.app.shell.render_browser_open, folded); + assert_eq!((h.app.cam, h.app.session.camera), camera); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), state); + assert!(!Harness::new().app.shell.render_focus); + } +} + +#[test] +fn render_workspace_focus_tab_only_toggles_render_without_text_focus() { + let mut h = Harness::new(); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(h.app.shell.render_focus); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-search"}})).unwrap(); + assert!(h.ctx.egui_wants_keyboard_input()); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); +} + +#[test] +fn render_workspace_compact_browser_card_and_focus_preserve_remembered_widths() { + for side in ["left", "right"] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 320.0; + h.app.preferences.render_inspector_width = 360.0; + h.frames(3); + for width in [1100, 900, 700] { + h.call("ui.resize", json!({"width":width,"height":700})); + h.frames(3); + if width == 700 { + h.step(&json!({"click":{"handle":"render:browser:show"}})).unwrap(); + h.frames(3); + let (browser, reservation) = h.app.shell.workspace_panels["render:browser"]; + let (inspector, _) = h.app.shell.workspace_panels["render:inspector"]; + assert!(reservation.is_none(), "narrow Browser overlays the canvas"); + assert!(!browser.intersect(inspector).is_positive()); + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + h.app.run("view.render_focus", json!({"on":false})).unwrap(); + h.frames(3); + assert!(h.app.shell.render_browser_open); + assert!(h.app.shell.workspace_panels.contains_key("render:browser")); + h.step(&json!({"click":{"handle":"render:browser:hide"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + assert_eq!(h.app.preferences.render_browser_width, 320.0); + assert_eq!(h.app.preferences.render_inspector_width, 360.0); + } + h.call("ui.resize", json!({"width":1400,"height":900})); + h.frames(3); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0.width(), 320.0); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), 360.0); + } +} + +#[test] +fn render_workspace_focus_messages_have_five_complete_locales() { + let keys = [ + "cmd.view.render_focus", + "cmd.view.render_browser", + "render.exit_focus", + "render.fold_browser", + "render.spot_cone", + "render.emitted_axis", + "render.inner_half_angle", + "render.outer_half_angle", + "render.layer_off_suffix", + "render.tone_reinhard", + "render.tone_aces_fitted", + "render.size_hd", + "render.size_full_hd", + "render.size_4k_uhd", + "render.result_actual_size", + "render.property_unknown", + "render.property_fallback", + "render.property_source", + "render.property_qualifier", + "render.property_conditions", + "render.property_uncertainty", + "render.error_setup_panicked", + "render.error_setup_worker", + "render.error_setup_stopped", + "render.error_gpu_samples", + "render.error_preview_device", + "render.error_finish_operation", + "render.error_no_completed_image", + "render.error_provisional_identity", + "render.error_checkpoint_dimensions", + "render.error_display_dimensions", + "render.error_display_fit", + "render.error_display_width", + "render.error_display_height", + "render.error_image_profile", + "render.error_decode_budget", + "render.error_image_dimensions", + "render.error_upload_slot", + "render.error_export_document", + "render.error_geometry_size", + "render.error_vertex_envelope", + "render.error_body_bound", + "render.error_triangle_count", + "render.error_triangle_bound", + "render.error_face_cap", + "render.error_opacity", + "render.error_duplicate_face", + "render.error_pbr_opacity", + "render.error_vertex_allocation", + "render.error_product_triangle", + "render.error_surface_normals", + "render.error_vertex_packing", + "render.error_gpu_preview", + "render.error_fixed_preview", + "render.error_finish_gesture", + "render.error_no_scene", + "render.error_no_geometry", + "render.error_visible_solid", + "render.error_area_samples", + "render.error_quality_method", + "render.error_quality_projection", + "render.error_denoise_setting", + "render.error_quality_bounds", + "render.error_library_reply", + "render.error_source_preview", + "render.error_glass_recipe", + "render.error_physical_glass", + "render.error_scene_bodies", + "render.error_scene_body_limit", + "render.error_scene_identity", + "render.error_material_binding", + "render.error_surface_reply", + "render.error_binding_allocation", + "render.error_job_identity", + "render.error_regrade_identity", + "render.error_job_action", + "render.error_interactive_command", + ]; + for (language, source) in [ + ("en", include_str!(concat!(env!("OUT_DIR"), "/locales/en.json"))), + ("ja", include_str!(concat!(env!("OUT_DIR"), "/locales/ja.json"))), + ("zh", include_str!(concat!(env!("OUT_DIR"), "/locales/zh.json"))), + ("de", include_str!(concat!(env!("OUT_DIR"), "/locales/de.json"))), + ("ko", include_str!(concat!(env!("OUT_DIR"), "/locales/ko.json"))), + ] { + let translated: std::collections::BTreeMap = serde_json::from_str(source).unwrap(); + let locale = crate::i18n::Locale::for_language(language); + for key in keys { + let value = translated.get(key).unwrap_or_else(|| panic!("{language}: missing {key}")); + assert!(!value.is_empty()); + assert_eq!(locale.text(key), value); + } + let sentence = locale.format("render.property_source", &[("id", "A"), ("locator", "B")]); + assert!(sentence.contains('A') && sentence.contains('B') && !sentence.contains('{')); + } +} + +#[test] +fn render_workspace_chrome_uses_tokens_instead_of_literal_colours() { + use syn::visit::{self, Visit}; + #[derive(Default)] + struct Colours(Vec); + impl<'ast> Visit<'ast> for Colours { + fn visit_expr_path(&mut self, expr: &'ast syn::ExprPath) { + let names: Vec<_> = expr.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") && names.last().is_some_and(|s| matches!(s.as_str(), "WHITE" | "BLACK" | "GRAY")) { + self.0.push(names.join("::")); + } + visit::visit_expr_path(self, expr); + } + fn visit_expr_call(&mut self, expr: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = expr.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") + && names.last().is_some_and(|s| s.starts_with("from_rgb") || s == "from_gray") + && expr.args.iter().all(|arg| matches!(arg, syn::Expr::Lit(_))) + { + self.0.push(names.join("::")); + } + } + visit::visit_expr_call(self, expr); + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files: Vec<_> = std::fs::read_dir(&root) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|path| { + let name = path.file_name().unwrap().to_string_lossy(); + name.starts_with("render_workspace") && name.ends_with(".rs") && !name.contains("tests") + }) + .collect(); + let mut folders = vec![root.join("render_ui")]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else if path.extension().is_some_and(|e| e == "rs") { + files.push(path); + } + } + } + for path in files { + let source = std::fs::read_to_string(&path).unwrap(); + let mut colours = Colours::default(); + colours.visit_file(&syn::parse_file(&source).unwrap()); + assert!(colours.0.is_empty(), "{}: {:?}", path.display(), colours.0); + } +} + +#[test] +fn render_workspace_shots_toggle_persists_and_design_roundtrip_preserves_state() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Subject".into() }]; + h.app.cam.yaw = 0.71; + h.app.cam.pitch = 0.23; + h.app.cam.roll = 0.17; + let camera = h.app.cam; + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let state = ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed, + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() <= 1.0, "{strip:?}"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.session.doc, document); + assert_eq!( + state, + ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed + ) + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_none()); + assert!(crate::scenario::rect_of("render:shots:show").is_some()); + h.step(&json!({"click":{"handle":"render:shots:show"}})).unwrap(); + assert!(h.app.preferences.render_shots_strip); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + let saved = h.app.prefs(); + let mut next = Harness::new(); + next.app.load_prefs(&saved); + assert!(!next.app.preferences.render_shots_strip); + h.frames(2); + h.app.start("view.shots_strip"); + assert!(h.app.preferences.render_shots_strip); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_some()); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), state.0); +} + +#[test] +fn render_workspace_canvas_controls_and_fit_respect_panels_and_shots_in_both_layouts() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":60,"width":40,"height":30})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.cam.fov = 0.9; + h.app.start("render.camera.fit"); + h.frames(4); + assert_eq!(h.app.cam.fov, 0.9); + let free = crate::shell::content_rect(&h.app, h.app.viewport.rect.unwrap()); + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(free.contains_rect(layout.navigation), "{free:?} {layout:?}"); + assert!((layout.navigation.center().x - free.center().x).abs() < 1.0); + assert_product_fits_canvas(&h.app); + } +} + +#[test] +fn render_workspace_old_personal_pins_migrate_once_to_task_tabs() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER/SCENE":["render.settings.get","render.preset.resolve","solid.box"], + "DESIGN/RENDER/LIGHTING":["render.library.studio.apply"], + "DESIGN/RENDER/CAMERA":["render.settings.apply","render.camera.fit"], + "DESIGN/RENDER/IMAGE":["render.export","render.start"], + "DESIGN/RENDER/OUTPUT":["render.preflight"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/SHOTS"], ["render.settings.get", "solid.box"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.preset.resolve", "render.library.studio.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/VIEW"], ["render.settings.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.start", "render.preflight"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +#[test] +fn render_workspace_scene_vocabulary_migrates_previous_shell_pins_once() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER LIGHTING/LIGHTING":["render.library.studio.apply","render.lights.solo"], + "DESIGN/RENDER LIGHTING/ENVIRONMENT":["render.library.environment.apply","render.hdr.inspect"], + "DESIGN/RENDER/OUTPUT":["render.preflight","render.quality.prepare"], + "DESIGN/RENDER/RESULTS":["render.export","render.effects.describe"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.library.studio.apply", "render.library.environment.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/LIGHTS"], ["render.lights.solo"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STAGE"], ["render.hdr.inspect"]); + assert_eq!(custom.panels["DESIGN/RENDER/IMAGE"], ["render.quality.prepare", "render.effects.describe"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.preflight"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +fn assert_product_fits_canvas(app: &SolveApp) { + let layout = app.viewport.layout.as_ref().unwrap(); + let free = crate::shell::content_rect(app, layout.viewport); + assert!(free.contains_rect(layout.drawable), "fit region {:?} outside canvas {free:?}", layout.drawable); + let bounds = solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (sx, sy, _) = app + .cam + .to_screen( + solidcraft_engine::geom::Vec3::new(x, y, z), + f64::from(layout.viewport.width()), + f64::from(layout.viewport.height()), + bounds.diagonal().max(10.0), + ) + .unwrap(); + let at = layout.viewport.min + egui::vec2(sx as f32, sy as f32); + assert!(layout.drawable.contains(at), "product corner {at:?} outside {:?}", layout.drawable); + } + } + } +} + +#[test] +fn render_workspace_hosts_float_and_shield_input_in_both_ribbon_layouts() { + for (layout, page) in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] + .into_iter() + .flat_map(|layout| [inspector::Page::Scene, inspector::Page::Appearance].map(|page| (layout, page))) + { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":30,"width":20,"height":10})).unwrap(); + h.frames(4); + + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = page; + h.frames(4); + let viewport = h.app.viewport.rect.unwrap(); + let history = crate::timeline::floating_rect(viewport); + let shots = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((shots.height() - 48.0).abs() <= 1.0, "{layout:?}: {shots:?}"); + assert!( + (shots.left() - history.left()).abs() < 1.0 + && (shots.right() - history.right()).abs() < 1.0 + && (shots.bottom() - history.bottom()).abs() < 1.0, + "Shots must reuse History's floating placement: {shots:?} {history:?}" + ); + for key in ["render:inspector", "render:browser", "render:appearances", "render:shots_strip"] { + let (card, _) = h.app.shell.workspace_panels.get(key).unwrap(); + assert!(viewport.contains_rect(*card), "{layout:?} {key}: {card:?} outside {viewport:?}"); + assert!(crate::shell::covered(&h.app, card.center()), "{key} must shield the viewport"); + } + let inspector = h.app.shell.workspace_panels["render:inspector"].0; + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + let ribbon_bottom = h.app.shell.cards.iter().map(|r| r.bottom()).fold(0.0, f32::max); + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!((appearances.bottom() - inspector.bottom()).abs() < 1.0); + assert!(browser.height() <= 330.0, "Browser must stay within the fixed tree height: {browser:?}"); + for key in ["render:browser", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + assert!( + (card.top() - ribbon_bottom - Tokens::get().space_8).abs() < 1.0, + "{layout:?} {key}: gap {} must be 8 pt", + card.top() - ribbon_bottom + ); + } + for key in ["render:browser", "render:appearances", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + let header = crate::scenario::rect_of(&format!("{key}:header")).unwrap(); + assert!((header.height() - crate::ui_kit::header_height()).abs() < 0.1, "{key}: {header:?}"); + assert!((header.top() - card.top()).abs() <= 1.0, "header must have no outer content padding"); + let control = crate::scenario::rect_of(if key == "render:browser" { + "render:tree:by-look" + } else if key == "render:appearances" { + "render:library-search" + } else if page == inspector::Page::Appearance { + "dialog:editor_footer" + } else { + "render:scene:look" + }) + .unwrap(); + if key == "render:browser" { + assert!(header.contains_rect(control), "Scene lens belongs in the title band"); + } else { + assert!(control.top() >= header.bottom(), "editor controls must be below the standard header: {control:?} {header:?}"); + } + } + + assert!((browser.width() - appearances.width()).abs() < 1.0); + assert!((appearances.top() - browser.bottom() - Tokens::get().space_8).abs() < 1.0); + assert!(appearances.bottom() < shots.top()); + assert!(browser.left() > viewport.left() && inspector.right() < viewport.right()); + assert!(inspector.bottom() < shots.top() && browser.bottom() < shots.top()); + let camera = h.app.cam; + h.step( + &json!({"drag":[[inspector.center().x,inspector.center().y],[inspector.center().x-30.0,inspector.center().y+20.0]],"button":"middle"}), + ) + .unwrap(); + assert_eq!(h.app.cam, camera, "middle dragging over the card must not reach the model"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.viewport.rect, Some(viewport), "floating strips must preserve the viewport projection"); + let pill = h.app.shell.workspace_panels["render:shots:show"].0; + assert!(crate::shell::covered(&h.app, pill.center())); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert!(h.app.shell.workspace_panels.is_empty(), "Render card reservations must not leak into Design"); + } +} + +#[test] +fn render_workspace_assignment_footer_fits_stacked_card_with_shots_shown_and_hidden() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + for shown in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shown})).unwrap(); + h.frames(4); + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + // Assignment help is the shared footer's tooltip; its visible anchor stays in the card. + let footer = crate::scenario::rect_of("catalog:footer").unwrap(); + assert!(appearances.contains_rect(footer), "{layout:?}, Shots {shown}: footer {footer:?} outside {appearances:?}"); + let gap = Tokens::get().space_8; + assert!((appearances.top() - browser.bottom() - gap).abs() < 1.0); + let bounds = crate::shell::panel_bounds(&h.app, h.app.viewport.rect.unwrap()); + assert!((bounds.bottom() - appearances.bottom() - gap).abs() < 1.0, "{layout:?}, Shots {shown}: {appearances:?}, {bounds:?}"); + } + } +} + +#[test] +fn render_workspace_card_grips_swap_sides_and_resize_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + h.step(&json!({"drag":[{"handle":"render:inspector:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, "left"); + assert_eq!(h.app.preferences.render_browser_side, "right"); + assert!(h.app.shell.workspace_panels["render:inspector"].0.right() < h.app.shell.workspace_panels["render:browser"].0.left()); + let width = h.app.preferences.render_inspector_width; + let card_width = h.app.shell.workspace_panels["render:inspector"].0.width(); + let rail = crate::scenario::handle_at("render:inspector:resize").unwrap(); + h.step(&json!({"drag":[[rail.x,rail.y],[rail.x+50.0,rail.y]],"steps":8})).unwrap(); + h.frames(3); + // A compact dock keeps its minimum width and leaves the remembered width alone. + if layout == crate::shell::LayoutMode::Docked { + assert_eq!(h.app.preferences.render_inspector_width, width); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), card_width); + } else { + assert!(h.app.preferences.render_inspector_width > width); + assert!(h.app.shell.workspace_panels["render:inspector"].0.width() > card_width); + } + h.step(&json!({"click":{"handle":"render:tree:by-look"}})).unwrap(); + h.frames(3); + h.step(&json!({"drag":[{"handle":"render:browser:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_browser_side, "left"); + assert_eq!(h.app.preferences.render_inspector_side, "right"); + assert!(h.app.shell.workspace_panels["render:browser"].0.right() < h.app.shell.workspace_panels["render:inspector"].0.left()); + assert_eq!(h.app.cam, camera, "card gestures must not move the camera"); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } +} + +/// A small public-safe model, built through the sample recipe inside an occurrence. +fn render_pick_sample() -> (Harness, u64) { + let mut h = Harness::new(); + let part = h.app.run("component.create", json!({"name":"Sample","grounded":false})).unwrap(); + let occurrence = part["occurrence"].as_u64().unwrap(); + h.app.session.run_script(&solidcraft_engine::sample::script()).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.start("render.camera.fit"); + h.settle(); + (h, occurrence) +} + +fn product_pick_point(h: &Harness) -> egui::Pos2 { + let rect = h.app.viewport.layout.as_ref().unwrap().drawable; + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + for y in 2..18 { + for x in 2..18 { + let at = rect.min + egui::vec2(rect.width() * x as f32 / 20.0, rect.height() * y as f32 / 20.0); + if !crate::shell::covered(&h.app, at) + && crate::viewport::pick(&h.app, &proj, at).iter().any(|h| matches!(h, crate::viewport::Hit::Face { .. })) + { + return at; + } + } + } + panic!("sample must offer a visible product face outside the floating panels"); +} + +#[test] +fn render_workspace_pick_stage_tools_filter_sample_clicks_with_shots_shown_and_hidden() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for shots in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shots})).unwrap(); + h.frames(3); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert!(tools.contains_rect(crate::scenario::rect_of("render:pick").unwrap())); + assert!(tools.contains_rect(crate::scenario::rect_of("render:preview_note").unwrap())); + assert!(crate::scenario::rect_of("render:hud").is_none()); + for mode in ["body", "face", "component"] { + assert!(crate::scenario::handle_at(&format!("render:pick:{mode}")).is_some(), "Pick must be enabled"); + h.step(&json!({"click":{"handle":format!("render:pick:{mode}")}})).unwrap(); + h.frames(2); + let at = product_pick_point(&h); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + assert!(matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. }))); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + match h.app.session.selection.as_slice() { + [Sel::Body { name }] if mode == "body" => assert_eq!(name, "Plate"), + [Sel::Face { body, .. }] if mode == "face" => assert_eq!(body, "Plate"), + [Sel::Occurrence { path }] if mode == "component" => assert_eq!(path, &[occurrence]), + other => panic!("{mode}, Shots {shots}: wrong selection {other:?}"), + } + let selected = h.app.session.selection.clone(); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.session.selection, selected); + enter(&mut h.app, true).unwrap(); + h.settle(); + assert_eq!(h.app.session.selection, selected); + } + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.tool.is_none() && h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_click_modifiers_clear_and_browser_share_selection() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + for (name, x) in [("Left", -30), ("Right", 30)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":20,"width":20,"height":20,"body_name":name})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.settle(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let left = proj.to_screen(solidcraft_engine::geom::Vec3::new(-20.0, 10.0, 20.0)).unwrap(); + let right = proj.to_screen(solidcraft_engine::geom::Vec3::new(40.0, 10.0, 20.0)).unwrap(); + h.step(&json!({"click":[left.x,left.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + h.step(&json!({"click":[left.x,left.y],"ctrl":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + h.app.preferences.selection_shift_add_only = true; + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + // A Browser body row writes the same selection and immediately feeds the product overlay. + h.step(&json!({"click":{"handle":"row:Left"}})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + assert!(!crate::viewport::build_highlight(&h.app).merged().tris.is_empty()); + let empty = h.app.viewport.layout.as_ref().unwrap().drawable.left_bottom() + egui::vec2(10.0, -10.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.session.selection.is_empty()); + assert!(h.app.viewport.hover.is_none()); +} + +#[test] +fn render_workspace_selection_overlay_never_changes_started_frames_png_or_retained_results() { + use solidcraft_engine::Sel; + let (mut h, _) = render_pick_sample(); + let at = product_pick_point(&h); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let hit = crate::viewport::pick(&h.app, &proj, at).into_iter().next().unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let first = completed_preview(&mut h, [230, 230, 230]); + let clean = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + let clean_scene = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + h.app.run("select.set", json!({"items":[face]})).unwrap(); + let face_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(!face_overlay.tris.is_empty()); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Plate".into() }]})).unwrap(); + let body_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(body_overlay.tris.len() > face_overlay.tris.len(), "Face must only tint the selected face"); + h.app.viewport.hover = Some(hit); + let second = completed_preview(&mut h, [230, 230, 230]); + let selected = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + assert_eq!(clean.png(), selected.png(), "started image job must never capture selection or hover pixels"); + let after = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + assert_eq!(clean_scene.0, after.0); + assert_eq!(clean_scene.1.tris, after.1.tris); + h.app.render_workspace.view.completed = Some(second); + h.app.render_workspace.view.result = true; + h.frames(3); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + h.step(&json!({"click":{"handle":"render:pick:body"}})).unwrap(); + assert!(!h.app.ui.pick_bodies && !h.app.ui.pick_components, "result canvas must disable the stage's Pick control"); + let path = h.dir.join("overlay-free.png"); + h.app.run("render.export", json!({"job":second,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), clean.png()); + assert_eq!(h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap().png(), clean.png()); +} + +#[test] +fn render_workspace_pick_filter_rejects_invalid_requests_atomically() { + let mut h = Harness::new(); + let doc = h.app.session.doc.clone(); + for mode in ["body", "face", "component"] { + assert_eq!(h.app.run("select.filter", json!({"mode":mode})).unwrap()["mode"], mode); + assert_eq!(h.app.ui.pick_bodies, mode == "body"); + assert_eq!(h.app.ui.pick_components, mode == "component"); + } + for request in [json!({}), json!({"mode":"edge"}), json!({"mode":"body","extra":true})] { + assert!(h.app.run("select.filter", request).is_err()); + assert!(!h.app.ui.pick_bodies && h.app.ui.pick_components); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(h.app.session.undo.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_product_pass_draws_only_requested_face_or_body_overlay() { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(256.0, 256.0)); + app.viewport.rect = Some(rect); + let proj = crate::viewport::projection(&app, rect); + let hit = crate::viewport::pick(&app, &proj, rect.center()).into_iter().find(|h| matches!(h, crate::viewport::Hit::Face { .. })).unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&app.session).unwrap(); + let gpu = gpu_scene(&scene).unwrap().1; + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(app.cam.target); + let eye = app.cam.eye().to_f32(); + let camera = app.cam; + let draw = |overlay| { + crate::gpu::render_product_offscreen( + gpu.clone(), + overlay, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 1.0], + 256, + false, + ) + }; + let Some(clean) = draw(None) else { + eprintln!("skipping: no GPU adapter for product overlay pixels"); + return; + }; + app.run("select.set", json!({"items":[face]})).unwrap(); + let face_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + app.run("select.set", json!({"items":[{"type":"body","name":"Product"}]})).unwrap(); + let body_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + let changed = |image: &[u8]| clean.as_chunks::<4>().0.iter().zip(image.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); + assert!(changed(&face_pixels) > 100, "Face overlay must reach the product pass"); + assert!(changed(&body_pixels) > changed(&face_pixels) + 100, "Face must leave the other faces untouched"); +} + +#[test] +fn render_workspace_pick_projection_matches_orthographic_and_custom_perspective_camera() { + use egui::{Event, Modifiers, PointerButton}; + use solidcraft_engine::geom::Vec3; + for fov in [0.0, 0.6, 1.1] { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + app.cam.fov = fov; + let ctx = crate::fonts::test_context(); + let mut time = 0.0; + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let rect = app.viewport.rect.unwrap(); + let proj = crate::viewport::projection(&app, rect); + assert_eq!(proj.cam.fov, fov); + let (x, y, _) = app.cam.to_screen(Vec3::new(20.0, 15.0, 20.0), f64::from(rect.width()), f64::from(rect.height()), 100.0).unwrap(); + let pos = rect.min + egui::vec2(x as f32, y as f32); + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(pos)]); + assert!(matches!(app.viewport.hover, Some(crate::viewport::Hit::Face { .. })), "FOV {fov}"); + for pressed in [true, false] { + nav_frame( + &mut app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], + ); + } + assert!(matches!(app.session.selection.as_slice(), [solidcraft_engine::Sel::Face { body, .. }] if body == "Product"), "FOV {fov}"); + } +} + +#[test] +fn render_workspace_component_filter_keeps_nested_repeated_occurrences_distinct() { + use crate::viewport::{Hit, candidate}; + use solidcraft_engine::{Sel, geom::Vec3}; + let mut h = Harness::new(); + let parent = h.app.run("component.create", json!({"name":"Parent"})).unwrap(); + let child = h.app.run("component.create", json!({"name":"Part"})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Solid"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"occurrence":parent["occurrence"],"translate":[50,0,0]})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"component"})).unwrap(); + for top in [parent["occurrence"].as_u64().unwrap(), second["occurrence"].as_u64().unwrap()] { + let path = vec![top, child["occurrence"].as_u64().unwrap()]; + let names = h.app.session.occurrence_bodies(&path, true).unwrap(); + assert_eq!(names.len(), 1); + let hit = Hit::Face { body: names[0].clone(), index: 0, point: Vec3::ZERO }; + assert_eq!(candidate(&h.app, &[hit]).unwrap().1, Sel::Occurrence { path }); + } +} + +#[test] +fn navigation_bar_render_canvases_filter_slots_and_keep_product_fit() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.preferences.look_at_anim = false; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps::RENDER); + // The product preview picks (#6426), so the slots that need a pick are on the bar there too. + for slot in ["orbit", "pan", "zoom", "fit", "look_at", "home", "visual_style", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } + h.app.cam.pan(100.0, 50.0, 600.0); + let panned = h.app.cam; + h.step(&json!({"click":{"handle":"nav:slot:fit"}})).unwrap(); + assert_ne!(h.app.cam.target, panned.target, "Fit recentres the product"); + assert_product_fits_canvas(&h.app); + let mut iso = h.app.cam; + iso.set_view(solidcraft_engine::render::StandardView::Iso); + h.app.cam.orbit(0.4, 0.2); + h.step(&json!({"click":{"handle":"nav:slot:home"}})).unwrap(); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (iso.yaw, iso.pitch), "Home returns to the isometric view"); + assert_product_fits_canvas(&h.app); + + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps { orbit: false, pick: false }); + for slot in ["orbit", "look_at", "visual_style"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_none(), "{slot}"); + } + for slot in ["pan", "zoom", "fit", "home", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } +} + +#[test] +fn render_lights_browser_sections_and_lights_describe_current_job_entries() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rows: Vec<_> = crate::browser::drawn_rows().into_iter().map(|r| r.0).collect(); + for section in ["Environment", "Lights", "Shots", "Objects"] { + assert!(rows.iter().any(|label| label == section), "{section}: {rows:?}"); + } + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3]); + assert_eq!(scene::environment(&h.app).0, "Fixed studio"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "lights":[{"direction":[0,0,-1],"color":[1,1,1],"intensity":1}], + "punctual_lights":[ + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1}, + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1, + "cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}} + ], + "area_lights":[{"center_mm":[0,0,10],"edge_u_mm":[1,0,0],"edge_v_mm":[0,-1,0],"color":[1,1,1],"intensity":1}] + })) + .unwrap(); + assert_eq!(scene::light_types(&h.app), ["render.tree_directional", "render.tree_point", "render.tree_spot", "render.tree_rectangle"]); + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.punctual_lights = None; + h.app.render_workspace.view.raytrace.area_lights = None; + assert!(scene::light_types(&h.app).is_empty(), "empty explicit rig must stay empty"); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let studio = &mut h.app.render_workspace.view.studio; + studio.sun_enabled = true; + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3], "implicit studio sources are listed"); + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app + .render_workspace + .view + .studio + .area_lights + .push(serde_json::from_value(json!({"center":[0,0,10],"u":[1,0,0],"v":[0,-1,0],"radiance":[1,1,1]})).unwrap()); + assert_eq!(scene::light_types(&h.app), ["render.tree_sun", "render.tree_rectangle"]); + h.app.render_workspace.view.studio.environment = studio::Environment::Sky; + h.app.render_workspace.view.studio.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.studio.intensity = 2.5; + assert_eq!(scene::environment(&h.app), ("Sky".into(), "90° · 2.50×".into())); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:environment:current"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + h.step(&json!({"click":{"browser":"Key"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); +} + +#[test] +fn render_workspace_browser_look_lens_counts_distinct_objects_and_selects_them() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + for (name, x) in [("A", 0), ("B", 20), ("C", 40)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + h.app.run("appearance.assign", json!({"bodies":["A","B"],"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["C"],"appearance":"ABS - Blue"})).unwrap(); + // Two faces on C use the same look as A and B: still only one additional user. + h.app.run("appearance.assign", json!({"body":"C","faces":[[40,5,5],[45,0,5]],"appearance":"ABS - Red"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let groups = scene::groups(&h.app); + let red = groups.iter().position(|g| g.look.as_ref().is_some_and(|l| l.name == "ABS - Red")).unwrap(); + assert_eq!(groups[red].objects, ["A", "B", "C"]); + assert_eq!(groups.len(), 2); + h.app.render_workspace.view.by_look = true; + // Keep the object rows inside the ten-row Browser viewport while testing their hover. + crate::browser::toggle(&mut h.app, "render:tree:lights", true); + h.frames(3); + let at = crate::scenario::handle_at("row:A").unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.frames(2); + assert_eq!(h.app.viewport.hover_bodies, ["A"], "By look rows retain Browser hover outlines"); + h.step(&json!({"move":[1000.0,800.0]})).unwrap(); + h.frames(2); + assert!(h.app.viewport.hover_bodies.is_empty(), "leaving the row clears its hover outline"); + h.step(&json!({"click":{"handle":format!("render:tree:look:{red}")}})).unwrap(); + assert_eq!(h.app.session.selection.len(), 3); + for name in ["A", "B", "C"] { + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: name.into() })); + } + h.step(&json!({"click":{"handle":"eye:A"}})).unwrap(); + assert!(h.app.session.visibility.hidden_bodies.contains(&"A".into())); + let menu = crate::context_menu::items(&h.app, &crate::context_menu::Target::Body { name: "A".into() }); + for id in ["select.set", "select.same_look", "ui.isolate", "ui.show"] { + assert!(menu.iter().any(|i| i.id == id)); + } +} + +#[test] +fn render_workspace_dock_command_swaps_sides_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + let product_camera = h.app.render_workspace.view.draft.camera; + let widths = (h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width); + assert!(crate::shortcut_box::search(&h.app, "view.render_dock").iter().any(|row| row.0 == "view.render_dock")); + for (panel, side, inspector, browser) in [ + ("inspector", "left", "left", "right"), + ("browser", "left", "right", "left"), + ("inspector", "right", "right", "left"), + ("browser", "right", "left", "right"), + ] { + h.app.run("view.render_dock", json!({"panel":panel,"side":side})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, inspector); + assert_eq!(h.app.preferences.render_browser_side, browser); + let a = h.app.shell.workspace_panels["render:inspector"].0; + let b = h.app.shell.workspace_panels["render:browser"].0; + assert_eq!(a.center().x < b.center().x, inspector == "left"); + let view = h.app.viewport.layout.as_ref().unwrap(); + assert!(view.content.contains_rect(view.axis_view)); + let edge = if inspector == "left" { view.axis_view.left() - view.content.left() } else { view.content.right() - view.axis_view.right() }; + assert!(edge.abs() < 0.1); + assert!(!view.navigation.intersects(a)); + assert!(!view.navigation.intersects(b)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.camera, product_camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + assert_eq!((h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width), widths); + } + } +} + +#[test] +fn render_workspace_dock_grip_menus_dispatch_the_other_side() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + for panel in ["inspector", "inspector", "browser", "browser"] { + let before = h.app.preferences.render_inspector_side.clone(); + let at = crate::scenario::handle_at(&format!("render:{panel}:grip")).unwrap(); + for pressed in [true, false] { + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }, + ]); + } + h.frames(2); + // Opening the menu must not move either panel. + assert_eq!(h.app.preferences.render_inspector_side, before); + h.step(&json!({"click":{"handle":format!("render:{panel}:move_side")}})).unwrap(); + h.frames(3); + assert_ne!(h.app.preferences.render_inspector_side, before); + assert_ne!(h.app.preferences.render_inspector_side, h.app.preferences.render_browser_side); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + } + } +} + +#[test] +fn render_workspace_browser_shot_switch_keeps_the_existing_dirty_confirmation() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{"width":321,"job":{"method":"raster"}}})).unwrap(); + h.app.render_workspace.view.draft.width = 123; + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "A"); + assert!(inspector::confirmation_open(&h.app)); + h.step(&json!({"widget":h.app.tr("render.keep_editing")})).unwrap(); + assert_eq!(h.app.render_workspace.view.draft.width, 123); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "B"); + assert_eq!(h.app.render_workspace.view.draft.width, 321); + assert!(!h.app.render_workspace.view.dirty); +} + +#[test] +fn render_lights_browser_focus_covers_each_kind_without_design_edits() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + h.app.run("render.settings.set", json!({"name":"Shot","set":{"job":{"method":"raster"}}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.sun_enabled = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for label in ["Environment", "Lights", "Shots", "Objects", "Output"] { + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == label), "{label}"); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.step(&json!({"click":{"handle":"row:Object"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Object(vec![Sel::Body { name: "Object".into() }])); + h.step(&json!({"click":{"handle":"render:tree:environment"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + assert!(crate::scenario::rect_of("dialog:section:Source").is_some()); + assert!(h.app.session.selection.is_empty()); + let focused_revision = h.app.session.revision; + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Light(id) if id=="directional:0")); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:Shot"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Shot("Shot".into())); + // The browser is height-capped even in a tall window. Output is its last row, + // and published targets can lie below the scroll clip as more rows are added. + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + h.call("ui.scroll", json!({"x":browser.center().x,"y":(header.bottom()+browser.bottom())/2.0,"delta":-2000})); + h.frames(20); + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + let output = crate::scenario::handle_at("render:tree:output").unwrap(); + assert!( + browser.shrink(Tokens::get().space_8).contains(output) && output.y > header.bottom(), + "Output click must be inside the visible browser body" + ); + h.step(&json!({"click":{"handle":"render:tree:output"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert_eq!(h.app.session.revision, focused_revision, "semantic selection only refreshes the view when clearing object picks"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[test] +fn render_lights_browser_eye_and_solo_are_view_state_and_editor_opening_is_read_only() { + let mut h = render_lights_fixture(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Key")); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Fill")); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.step(&json!({"click":{"handle":"eye:Key"}})).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.step(&json!({"click":{"handle":"render:tree:light:1:solo"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), Some("directional:1")); + h.step(&json!({"click":{"handle":"render:tree:light:1"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + assert!(crate::scenario::handle_at("render:tree:shots:add").is_some()); + h.step(&json!({"click":{"handle":"render:tree:shots:add"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_browser_stage_expansion_never_locks_rows_or_changes_focus() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + let doc = h.app.session.doc.clone(); + let sections = ["objects", "lights", "environment", "shots"]; + for (stage, expanded) in [("look", vec!["objects"]), ("light", vec!["lights", "environment"]), ("frame", vec!["shots"]), ("output", vec![])] { + for section in sections { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + for section in sections { + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), expanded.contains(§ion), "{stage}/{section}"); + crate::browser::toggle(&mut h.app, &format!("render:tree:{section}"), true); + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), !expanded.contains(§ion)); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn render_workspace_browser_semantic_focus_survives_clearing_object_picks() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let doc = h.app.session.doc.clone(); + let evaluated = h.app.session.world_state(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for (request, expected) in [ + (json!({"kind":"environment"}), RenderSelection::Environment), + (json!({"kind":"lighting"}), RenderSelection::Lighting), + (json!({"kind":"light","id":"sun"}), RenderSelection::Light("sun".into())), + (json!({"kind":"shot","id":"Shot"}), RenderSelection::Shot("Shot".into())), + (json!({"kind":"output"}), RenderSelection::Output), + (json!({"kind":"nothing"}), RenderSelection::Nothing), + ] { + h.app.run("select.set", json!({"items":[Sel::Body { name:"Object".into() }]})).unwrap(); + assert!(matches!(h.app.render_workspace.view.selection, RenderSelection::Object(_))); + h.app.run("view.render_select", request.clone()).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, expected, "{request}"); + assert!(h.app.session.selection.is_empty()); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(Arc::ptr_eq(&evaluated, &h.app.session.world_state())); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); +} + +#[test] +fn render_workspace_browser_focus_is_per_document_and_invalid_selection_is_atomic() { + let mut h = Harness::new(); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let doc = h.app.session.doc.clone(); + for request in [ + json!({}), + json!({"kind":"object"}), + json!({"kind":"light"}), + json!({"kind":"shot","id":""}), + json!({"kind":"lighting","id":"extra"}), + json!({"kind":"output","id":"x"}), + json!({"kind":"shot","id":"x".repeat(1025)}), + json!({"kind":"nothing","extra":1}), + ] { + assert!(h.app.run("view.render_select", request).is_err()); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + crate::documents::switch(&mut h.app, 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); +} + +#[test] +fn render_workspace_wear_tree_selects_the_scene_stack_and_counts_layers_in_both_lenses() { + use solidcraft_engine::render::job::aging::{AgingKind, AgingLayer}; + fn has_text(shape: &egui::Shape, needle: &str) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.text().contains(needle), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, needle)), + _ => false, + } + } + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body { name: "Subject".into() }]})).unwrap(); + let document = h.app.session.doc.clone(); + assert_eq!(scene::wear_subtitle(&h.app), h.app.tr("render.wear_no_layers")); + h.frames(3); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, h.app.tr("render.wear_no_layers")))); + h.step(&json!({"click":{"handle":"render:tree:wear"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Wear); + assert!(h.app.session.selection.is_empty()); + assert!(crate::scenario::rect_of("render:wear:controls").is_some()); + assert!(!crate::icon_svg::resolve("appearance").placeholder); + for count in 1..=2 { + h.app.render_workspace.view.studio.aging.push(AgingLayer::preset(AgingKind::Dust)).unwrap(); + h.app.render_workspace.view.dirty = true; + let label = + crate::i18n::format(if count == 1 { "render.wear_layer_one" } else { "render.wear_layer_count" }, &[("count", &count.to_string())]); + assert_eq!(scene::wear_subtitle(&h.app), label); + for by_look in [false, true] { + h.app.run("view.render_browser", json!({"by_look":by_look})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:tree:wear").is_some()); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, &label))); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +/// Actual application tree at the approved card width, in both themes and both task states. +#[test] +fn render_workspace_browser_compact_geometry_search_and_theme_evidence() { + let previous = crate::theme::is_dark(); + let mut themes = Vec::new(); + for dark in [false, true] { + let mut h = Harness::new(); + for (name, x, appearance) in [ + ("Plate", 0, "Aluminum - Satin"), + ("Boss", 20, "Aluminum - Anodized Blue"), + ("Knob", 40, "Copper"), + ("Cover", 60, "Glass - Clear"), + ("Spacer", 80, "Aluminum - Satin"), + ("Bolt", 100, "Aluminum - Satin"), + ("Nut", 120, "Aluminum - Satin"), + ] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":[name],"appearance":appearance})).unwrap(); + } + let group = + h.app.run("browser.group", json!({"folder":"bodies","name":"Spacer, fasteners","items":["Spacer","Bolt","Nut"]})).unwrap()["group"] + .as_u64() + .unwrap(); + h.app.tree.collapsed.insert(format!("c0/g{group}")); + for name in ["Hero", "Front", "Detail"] { + h.app.run("render.settings.set", json!({"name":name,"set":{"width":1920,"height":1080}})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_width = 266.0; + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + h.app.ui.dark = dark; + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + let mut images = Vec::new(); + for stage in ["look", "light"] { + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = Some(serde_json::from_value(json!([{"direction":[0,0,-1],"color":[1,1,1],"intensity":1},{"direction":[1,0,0],"color":[1,1,1],"intensity":1},{"direction":[0,1,0],"color":[1,1,1],"intensity":1}])).unwrap()); + for section in ["lights", "shots", "objects"] { + if (stage == "look" && section == "objects") || (stage == "light" && section == "lights") { + h.app.tree.collapsed.remove(&format!("render:tree:{section}")); + } else { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + } + if stage == "light" { + h.app + .run( + "view.render_select", + json!({"kind":"light","id":format!("{}:render.tree_directional:0",h.app.render_workspace.view.method.label())}), + ) + .unwrap(); + } + let mut image = None; + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(bounds), + time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), + focused: true, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let card = crate::scenario::rect_of("browser:card").unwrap(); + assert!((card.width() - 266.0).abs() < 0.1); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let stage_panel = h.app.shell.workspace_panels["render:appearances"].0; + assert!((card.top() - inspector.top()).abs() < 0.1); + assert!((stage_panel.bottom() - inspector.bottom()).abs() < 0.1); + assert!((stage_panel.top() - card.bottom() - Tokens::get().space_8).abs() < 0.1); + assert!(card.height() <= 330.0, "Browser must stay within the fixed tree height: {card:?}"); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + assert!(header.contains_rect(crate::scenario::rect_of("render:tree:by-look").unwrap())); + assert!(crate::scenario::handle_at("render:browser-model").is_none()); + assert!(crate::scenario::handle_at("render:browser-library").is_none()); + for (name, row, _, _) in crate::browser::drawn_rows() { + assert!((row.height() - 28.0).abs() < 0.1, "{name}: {row:?}"); + } + if stage == "look" { + let row = crate::browser::drawn_rows().into_iter().find(|r| r.0 == "Boss").unwrap().1; + assert!((row.width() - (card.width() - 2.0)).abs() < 0.1); + assert!(crate::scenario::handle_at("eye:Boss").unwrap().x > row.right() - 24.0); + } + if std::env::var_os("SOLIDCRAFT_BROWSER_EVIDENCE").is_some() { + let full = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image = Some( + image::imageops::crop_imm(&full, card.left() as u32, card.top() as u32, card.width() as u32, card.height() as u32) + .to_image(), + ); + } + } + } + if let (Some(image), Ok(dir)) = (image, std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + std::fs::create_dir_all(&dir).unwrap(); + image.save(std::path::Path::new(&dir).join(format!("scene-{stage}-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + images.push(image); + } + } + if let (Some(look), Some(light), Ok(dir)) = (images.first(), images.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + let mut pair = image::RgbaImage::new(look.width() + light.width(), look.height().max(light.height())); + image::imageops::overlay(&mut pair, look, 0, 0); + image::imageops::overlay(&mut pair, light, 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-stages-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + themes.push(images); + h.app.run("view.render_browser", json!({"search":true,"query":"Copper"})).unwrap(); + h.app.tree.collapsed.remove("render:tree:objects"); + h.frames(4); + let rows = crate::browser::drawn_rows(); + assert!(rows.iter().any(|r| r.0 == "Knob")); + assert!(!rows.iter().any(|r| r.0 == "Boss")); + h.app.run("view.render_browser", json!({"search":false})).unwrap(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == "Boss")); + for hidden in [true, false] { + h.step(&json!({"click":{"handle":"eye:Boss"}})).unwrap(); + assert_eq!(h.app.session.visibility.hidden_bodies.iter().any(|name| name == "Boss"), hidden); + } + } + if let (Some(light), Some(dark), Ok(dir)) = (themes.first(), themes.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + for (index, stage) in ["look", "light"].iter().enumerate() { + let mut pair = image::RgbaImage::new(light[index].width() + dark[index].width(), light[index].height().max(dark[index].height())); + image::imageops::overlay(&mut pair, &light[index], 0, 0); + image::imageops::overlay(&mut pair, &dark[index], 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-{stage}-themes.png"))).unwrap(); + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_workspace_shots_modified_dot_update_and_revert_follow_only_camera() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + h.frames(3); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + h.app.render_workspace.view.draft.width = 317; + h.frames(2); + assert!(!shots::camera_modified(&h.app, "Studio"), "output settings must not mark the camera"); + h.app.cam.yaw += 0.3; + h.frames(3); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_some()); + assert!(crate::scenario::handle_at("render:shots:update").is_some()); + h.step(&json!({"click":{"handle":"render:shots:update"}})).unwrap(); + h.frames(2); + let mut expected = saved.clone(); + expected.camera = h.app.cam; + assert_eq!(h.app.session.doc.render.setups["Studio"], expected, "Update must preserve saved output and lighting"); + assert_eq!(h.app.render_workspace.view.draft.width, 317, "Update must preserve the editor draft"); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + assert!(crate::scenario::handle_at("render:shots:update").is_none()); + h.app.cam.roll += 0.2; + h.frames(3); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:revert"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.cam, expected.camera); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_shots_save_prompt_and_size_dropdown_use_existing_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:shots:save"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + h.app.render_workspace.view.save_shot_name = Some("Hero".into()); + h.frames(3); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(1.0)); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(h.app.session.doc.render.setups.contains_key("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.render.setups["Hero"].camera, h.app.cam); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:size"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:Full HD"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1920, 1080)); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_shots_thumbnails_bound_invalidate_and_never_replace_results_or_history() { + use std::time::{Duration, Instant}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + for index in 0..20 { + h.app.run("render.settings.set", json!({"name":format!("Shot {index:02}"),"set":{"camera":h.app.cam}})).unwrap(); + } + // A real completed frame stays available, including its exact PNG and retained texture. + let id = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + let png = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + let retained = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let deadline = Instant::now() + Duration::from_secs(20); + while h.app.render_workspace.thumbnails.entries.len() < thumbnails::LIMIT { + assert!(Instant::now() < deadline, "thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(h.app.render_workspace.thumbnails.entries.len(), 16); + assert!(h.app.render_workspace.thumbnails.entries.values().all(|texture| texture.as_ref().is_some_and(|texture| texture.size() == [104, 60]))); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), retained); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), png); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); + // Later shots must get previews on selection/scrolling rather than keeping the first 16 forever. + h.app.render_workspace.view.name = "Shot 19".into(); + h.app.render_workspace.thumbnails.show(vec!["Shot 18".into(), "Shot 19".into()], &h.ctx); + thumbnails::refresh(&mut h.app, &h.ctx); + while h.app.render_workspace.thumbnails.texture("Shot 19").is_none() || h.app.render_workspace.thumbnails.texture("Shot 18").is_none() { + assert!(Instant::now() < deadline, "visible thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.len() <= 16); + std::thread::sleep(Duration::from_millis(2)); + } + let old = h.app.render_workspace.thumbnails.entries.keys().cloned().collect::>(); + // Camera, scene revision and visibility invalidate stale previews. + let camera = Camera { yaw: 0.7, ..h.app.cam }; + h.app.run("render.settings.set", json!({"name":"Shot 00","set":{"camera":camera}})).unwrap(); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.keys().all(|key| !old.contains(key))); + h.app.session.visibility.hidden_bodies.push("Body1".into()); + thumbnails::refresh(&mut h.app, &h.ctx); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); + thumbnails::refresh(&mut h.app, &h.ctx); + reset_document(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); +} + +#[test] +fn render_workspace_shots_running_ring_stays_with_the_submitted_shot() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{}})).unwrap(); + h.app.start("render.start"); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("A")); + h.app.render_workspace.view.name = "B".into(); + h.frames(2); + assert!(crate::scenario::rect_of("dialog:list:shot:A:progress").is_some()); + assert!(crate::scenario::rect_of("dialog:list:shot:B:progress").is_none()); + h.app.start("render.cancel"); +} + +#[test] +fn render_workspace_shots_thumbnail_keys_include_name_scene_revision_and_complete_camera() { + let camera = Camera::default(); + let key = thumbnails::Key::new("Hero".into(), 1, 2, camera); + assert_eq!(key, thumbnails::Key::new("Hero".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Front".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 2, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 3, camera)); + for changed in [ + Camera { yaw: camera.yaw + 0.1, ..camera }, + Camera { roll: camera.roll + 0.1, ..camera }, + Camera { fov: 0.7, ..camera }, + Camera { up: solidcraft_engine::render::UpAxis::Y, ..camera }, + ] { + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 2, changed)); + } +} + +#[test] +fn render_workspace_shots_heading_matches_design_history_typography_and_strip_baseline() { + fn heading(h: &mut Harness, title: &str, strip: &str) -> (egui::FontId, Color32) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 1000.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + let rect = crate::scenario::rect_of(strip).unwrap(); + let text = crate::test_support::text_shapes(&output).find(|text| text.galley.text() == title && rect.contains(text.pos)).unwrap(); + let format = &text.galley.job.sections.first().unwrap().format; + assert!((text.pos.y + text.galley.size().y / 2.0 - rect.center().y).abs() <= 1.0, "{title} centred on its strip"); + let appearance = (format.font_id.clone(), format.color); + output.textures_delta.clear(); + appearance + } + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.ui.layout = crate::shell::LayoutMode::Docked; + h.app.preferences.timeline_left = false; + h.app.ui.show_timeline = true; + h.frames(3); + let history = heading(&mut h, "History", "history:strip"); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert_eq!(heading(&mut h, "Shots", "render:shots_strip"), history); +} + +#[test] +fn render_workspace_frame_save_shot_dispatches_without_a_ribbon_or_document_edits() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(3); + assert!(crate::scenario::handle_at("render:stage:save_shot").is_none()); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:stage:save_shot"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); + h.app.render_workspace.view.save_shot_name = Some("Frame shot".into()); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Frame shot"].camera, h.app.cam); + h.app.render_workspace.view.save_shot_name = None; + assert!(h.app.run("render.settings.set", json!({})).is_err()); + assert!(!inspector::confirmation_open(&h.app)); + assert!(crate::workspace::destination(solidcraft_engine::find_command("view.shots_strip").unwrap()).is_none()); + assert!(crate::workspace::RIBBON_LABELS.iter().all(|(id, _)| *id != "view.shots_strip")); +} + +#[test] +fn render_workspace_shots_strip_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.pending_fit = None; + for (name, yaw) in [("Hero", 0.5), ("Front", 0.0), ("Detail", 0.8)] { + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":Camera {yaw,..h.app.cam}}})).unwrap(); + } + switch_shot(&mut h.app, "Hero".into()); + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":1920,"height":1080}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..10_000 { + host.pump(16_384).unwrap(); + if h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some() { + break; + } + } + assert!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some()); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(bounds), time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() < 1.0, "{strip:?}"); + let mut last = crate::scenario::rect_of("render:shots:heading").unwrap(); + for target in [ + "render:shots:save", + "render:shots:setup:Detail", + "render:shots:setup:Front", + "render:shots:setup:Hero", + "render:shots:status", + "render:shots:size", + "render:shots:render", + "render:shots:hide", + ] { + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(strip.contains_rect(rect), "{target}: {rect:?} in {strip:?}"); + assert!(rect.left() >= last.right(), "{target} overlaps preceding control"); + last = rect; + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_SHOTS_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("shots-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn appearance_editor_hostile_optics_stay_finite_and_never_panic() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1e300] { + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass.ior = value; + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_err(), "hostile IOR {value}"); + } + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_ok(), "box boundaries are closed dielectrics too"); +} + +fn output_viewer_fixture() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.frames(3); + h +} + +#[test] +fn output_viewer_size_chips_obey_limits_and_largest_upscales_at_the_current_aspect() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for (key, expected) in [("720", (1280, 720)), ("1080", (1920, 1080))] { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + let draft = &h.app.render_workspace.view.draft; + assert_eq!((draft.width, draft.height), expected); + } + let largest = inspector::largest_output(&h.app).unwrap(); + assert!(largest.0 > 1920); + assert_eq!(cpu::image_limits(&h.app).fit(largest.0, largest.1, None), Some(largest)); + assert!((largest.0 as f64 / largest.1 as f64 - 16.0 / 9.0).abs() < 0.002); + h.step(&json!({"click":{"handle":"render:size:largest"}})).unwrap(); + assert_eq!((u64::from(h.app.render_workspace.view.draft.width), u64::from(h.app.render_workspace.view.draft.height)), largest); + let before = h.app.render_workspace.view.draft.clone(); + assert!(h.app.run("render.output.size", json!({"width":4096,"height":4096})).is_err()); + assert_eq!(h.app.render_workspace.view.draft, before); + assert_eq!(h.app.session.doc.features, document.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_check_lists_preflight_results_without_starting_and_marks_edits_stale() { + let mut h = output_viewer_fixture(); + let host = h.app.session.render_job_host().unwrap().clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:stage:check"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.checked.is_none()); + h.step(&json!({"click":{"handle":"render:check"}})).unwrap(); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + h.app.run("render.output.size", json!({"width":32,"height":16})).unwrap(); + h.frames(2); + assert!(crate::scenario::rect_of("render:check:stale").is_some()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_copy_uses_retained_final_pixels_and_refuses_missing_or_oversized_images() { + let mut h = output_viewer_fixture(); + assert!(ribbon::perform_job(&mut h.app, "render.result.copy").is_err()); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(decode_render_image(&[], 4097, 1, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + assert!(decode_render_image(&[], 4096, 4096, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + let first = completed_preview(&mut h, [12, 34, 56]); + h.app.render_workspace.view.completed = Some(first); + // A new queued render must not become the source for Copy. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + ribbon::perform_job(&mut h.app, "render.result.copy").unwrap(); + let image = h.app.render_workspace.clipboard_image.as_ref().unwrap(); + assert_eq!(image.size, [16, 16]); + assert_eq!(image.pixels[0], egui::Color32::from_rgb(12, 34, 56)); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame(); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(h.output.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyImage(image) if image.size == [16,16]))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); +} + +#[test] +fn output_viewer_progress_keeps_stage_tools_and_cancel_cancels_without_closing_viewer() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.result = true; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_some()); + assert!(crate::scenario::rect_of("render:stage:size").is_some()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + h.step(&json!({"click":{"handle":"render:progress-cancel"}})).unwrap(); + h.app.session.render_job_host().unwrap().pump(1024).unwrap(); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "cancelled"); + assert!(h.app.render_workspace.view.result); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_none()); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at("render:pick").is_some()); +} + +#[test] +fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cancelling() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.name = "Active shot".into(); + h.app.render_workspace.view.draft.width = 32; + h.app.render_workspace.view.draft.height = 24; + assert_eq!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); + h.step(&json!({"key":"R"})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Active shot")); + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["request"]["width"], 32); + assert_eq!(status["request"]["height"], 24); + // A repeated R while busy cannot fall through to Rectangle/Create Sketch. + h.step(&json!({"key":"R"})).unwrap(); + assert_eq!(h.app.render_workspace.view.job, Some(job)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.frames(2); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert!(ribbon::busy(&h.app), "closing the image never cancels the job"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); + crate::keymap::press(&mut h.app, "Escape", false); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.viewport.nav.is_none(), "closing the image releases its navigation capture"); + enter(&mut h.app, false).unwrap(); + assert_ne!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); +} + +/// Actual app controls and retained pixels, rasterized from egui without a window. +#[test] +fn output_viewer_evidence() { + let Some(dir) = std::env::var_os("SOLIDCRAFT_OUTPUT_EVIDENCE") else { return }; + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.run("solid.box", json!({"length":24,"width":18,"height":12})).unwrap(); + inspector::fit_subject(&mut h.app).unwrap(); + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.preferences.render_inspector_width = 305.0; + h.app.run("render.output.size", json!({"width":1280,"height":720})).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + h.ctx = crate::fonts::test_context(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + crate::theme::set_dark(dark); + crate::theme::apply(&h.ctx); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for (index, state) in ["settings", "check", "effects", "running", "completed"].into_iter().enumerate() { + if state == "check" { + h.app.run("view.render_select", json!({"kind":"check"})).unwrap(); + h.app.cancel_view_animation(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + if state == "effects" { + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.start("render.effects.describe"); + } + if state == "running" { + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + // Retain a real first image while the next job makes bounded progress. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.completed.is_some()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + host.pump(327680).unwrap(); + assert!(ribbon::busy(&h.app)); + } + if state == "completed" { + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + } + for frame in 0..10 { + let mut events = Vec::new(); + if frame == 0 { + events.push(egui::Event::PointerMoved(egui::pos2(700.0, 500.0))); + } + let mut input = egui::RawInput { + screen_rect: Some(bounds), + focused: true, + time: Some((index * 10 + frame) as f64 / 60.0), + events, + ..Default::default() + }; + h.app.raw_input_hook(&mut input); + let mut output = h.ctx.run_ui(input, |ui| { + h.app.logic(ui.ctx()); + if state == "check" && frame == 9 { + // Check the settled, scrolled view immediately before capturing it. + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + h.app.ui(ui); + }); + crate::ui_kit::update_test_textures(&mut textures, &output.textures_delta); + if frame == 9 { + if state == "check" { + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + assert!(h.app.render_workspace.view.job.is_none()); + } + crate::ui_kit::raster_ui(&h.ctx, output.shapes.clone(), output.pixels_per_point, bounds, &textures) + .save(dir.join(format!("output-{state}-{}.png", if dark { "dark" } else { "light" }))) + .unwrap(); + } + output.textures_delta.clear(); + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled() { + let h = output_viewer_fixture(); + let expected = [ + "render.start", + "appearance.assign", + "render.lights.add", + "render.settings.set", + "render.camera.fit", + "render.compare", + "ui.workspace.design", + "undo", + ]; + assert_eq!(crate::mouse_gesture::Studio::Render.defaults(), expected); + assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); + assert!(!crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); +} + +#[test] +fn output_viewer_presets_are_commands_with_limits_and_custom_keeps_the_size() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(6); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "opening Size presets does not apply anything"); + for (index, (key, expected)) in [("720", (1280, 720)), ("1080", (1920, 1080)), ("square", (2048, 2048))].into_iter().enumerate() { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), expected); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + let saved = &h.app.session.doc.render.setups[&h.app.render_workspace.view.name]; + assert_eq!((saved.width, saved.height), expected); + } + h.step(&json!({"click":{"handle":"render:preset:4k"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + h.step(&json!({"click":{"handle":"render:preset:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.resolution.custom); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + assert_eq!(document.features, h.app.session.doc.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to_output() { + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1440,"height":900})); + h.frames(3); + for key in ["render.children.renderer", "render.output_image", "render.output_destination", "render.children.render"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).is_some(), "{key}"); + } + assert!(crate::scenario::rect_of("render:job-footer").is_none()); + for page in ["output", "effects", "all"] { + assert!(crate::scenario::rect_of(&format!("render:page:{page}")).is_none()); + } + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for target in ["render:stage:size", "render:stage:check"] { + assert!(tools.contains_rect(crate::scenario::rect_of(target).unwrap())); + } + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:output-width").is_some(), "selected Output keeps its editor when the stage changes"); + } +} + +#[test] +fn render_assign_gestures_selection_sizes_are_atomic_and_undoable() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + for mode in ["body", "face", "component"] { + h.app.run("select.filter", json!({"mode":mode})).unwrap(); + let at = product_pick_point(&h); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), false).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + match mode { + "body" => assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"), + "face" => assert!(h.app.session.doc.appearances.faces.iter().any(|f| f.look.name == "ABS - Blue")), + _ => { + let id = h.app.session.doc.path_placement(&[occurrence]).unwrap().0; + assert_eq!(h.app.session.doc.appearances.components[&id].name, "ABS - Blue"); + } + } + assert!(h.app.status_undo); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Plate".into() }, Sel::Body { name: "missing".into() }]; + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assert!(assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_assign_gestures_paint_sample_copy_paste_escape_and_failed_pick() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let before = h.app.session.doc.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + h.frames(3); + let at = product_pick_point(&h); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + h.step(&json!({"widget":"Undo"})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1, "toast Undo must not paint through to the canvas"); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.run("appearance.assign", json!({"body":"Plate","faces":[[20,20,8]],"appearance":"ABS - Blue"})).ok(); + h.app.start("appearance.pick_up"); + let candidate = crate::viewport::pick(&h.app, &crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()), at) + .into_iter() + .find(|hit| matches!(hit, crate::viewport::Hit::Face { .. })) + .unwrap(); + let source = match candidate { + crate::viewport::Hit::Face { body, index, .. } => Some((body, index)), + _ => None, + }; + let (body, index) = source.unwrap(); + let expected = h.app.run("appearance.pick_up", json!({"target":{"body":body,"face":index}})).unwrap()["look"].clone(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert_eq!(h.app.render_workspace.view.assign.look, Some(expected.clone())); + h.step(&json!({"widget":"Done"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.start("appearance.paint"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Plate".into() }]; + h.app.start("appearance.copy"); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Yellow"})).unwrap(); + let undo = h.app.session.undo.len(); + h.app.start("appearance.paste"); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); + h.app.start("appearance.pick_up"); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + // Empty view: a failed pick neither paints nor exits sampling. + let free = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + let empty = egui::pos2(free.right() - 20.0, free.bottom() - 50.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.sampling); +} + +#[test] +fn render_assign_gestures_drag_preview_and_release_use_no_document_draft() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let at = product_pick_point(&h); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.frames(2); + assert!(assign::preview(&h.app).is_some()); + let mut scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let before = scene.meshes.iter().map(|m| m.color).collect::>(); + assign::preview_scene(&mut scene, assign::preview(&h.app).as_ref()).unwrap(); + assert_ne!(scene.meshes.iter().map(|m| m.color).collect::>(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.frame_with(vec![egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }]); + h.frames(2); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), document.to_json()); +} + +#[test] +fn render_assign_gestures_shortcuts_are_scoped_and_commands_are_not_stubs() { + let mut h = Harness::new(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("inspect.measure")); + enter(&mut h.app, true).unwrap(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("appearance.pick_up")); + assert_eq!(crate::keymap::command_for(&h.app, "B"), Some("appearance.paint")); + for (id, key) in [("appearance.copy", "Ctrl+Alt+C"), ("appearance.paste", "Ctrl+Alt+V")] { + assert_eq!(crate::keymap::command_for(&h.app, key), Some(id)); + } + for id in ["appearance.paint", "appearance.pick_up", "appearance.copy", "appearance.paste"] { + assert!(solidcraft_engine::find_command(id).unwrap().planned.is_none()); + } + let before = h.app.session.doc.clone(); + h.app.run("appearance.paint", json!({"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.pick_up", json!({})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(h.app.dialog.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[test] +fn render_assign_gestures_grid_drag_modifiers_cancel_and_context_menu() { + let (mut h, occurrence) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"name":"Gesture blue","color":"#1234dd"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.step(&json!({"click":{"handle":"render:library-scope:in-design"}})).unwrap(); + h.frames(3); + let id = json!(["Gesture blue", "#1234dd", 1.0, null]).to_string(); + let source = crate::scenario::rect_of(&format!("render:library:{id}")).unwrap().center(); + let at = product_pick_point(&h); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::PointerMoved(source)]); + h.frame_with(vec![egui::Event::PointerButton { + pos: source, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }]); + h.frame_with(vec![egui::Event::PointerMoved(source + egui::vec2(20.0, 0.0))]); + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frames(2); + assert!(assign::preview(&h.app).is_some(), "grid drag must arm a live preview over geometry"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for mods in [egui::Modifiers::SHIFT, egui::Modifiers::CTRL, egui::Modifiers::COMMAND] { + h.frame_with(vec![egui::Event::ModifiersChanged(mods)]); + h.frames(2); + let hover = assign::hover(&h.app).unwrap(); + if mods.shift { + assert!(matches!(hover, solidcraft_engine::Sel::Face { .. })); + } else { + assert_eq!(hover, &solidcraft_engine::Sel::Occurrence { path: vec![occurrence] }); + } + assert!(assign::preview(&h.app).is_some()); + } + h.frame_with(vec![ + egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::SHIFT }, + ]); + h.frames(2); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.faces.last().unwrap().look.name, "Gesture blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + let menu = assign::menu(&h.app, "Plate"); + for id in ["appearance.library", "appearance.pick_up", "appearance.copy", "appearance.paste", "appearance.assign"] { + assert!(menu.children.iter().any(|item| item.id == id), "missing menu action {id}"); + } + let browse = menu.children.iter().find(|item| item.id == "appearance.library").unwrap(); + crate::context_menu::run_item(&mut h.app, browse, at); + assert!(h.app.dialog.is_none()); + assert!(!h.app.render_workspace.view.assign.painting); +} + +#[test] +fn render_assign_gestures_labels_translate_in_all_five_catalogs() { + for language in ["en", "ja", "zh", "de", "ko"] { + let locale = crate::i18n::Locale::for_language(language); + for id in [ + "cmd.appearance_copy", + "cmd.appearance_paste", + "render.assign_help", + "render.browse_looks", + "render.choose_look", + "render.look_applied", + "render.painting_with", + "render.pick_up_prompt", + "render.recent_looks", + "render.remove_override", + "cmd.appearance_favorite", + "render.replace_all", + "render.replace_with", + "render.look_material", + "render.hover_look", + ] { + assert_ne!(locale.text(id), id, "{language}: {id}"); + } + assert!(locale.format("render.painting_with", &[("name", "Sample")]).contains("Sample")); + } +} + +#[test] +fn render_lighting_group_selection_opens_ordered_editor_and_plus_still_adds() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + let before = h.app.session.doc.clone(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:lighting:editor").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + let sections: Vec<_> = ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] + .iter() + .map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()) + .collect(); + assert!(sections.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); + h.step(&json!({"click":{"handle":"render:tree:lights:add"}})).unwrap(); + assert!(light::rows(&h.app).unwrap().iter().any(|l| l.geometry.kind() == "area")); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("area:0".into())); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_methods_show_reasons_and_budgets_without_changing_method_or_design() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + if method == ImageMethod::GpuRaytrace { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{}}}}})).unwrap(); + setups::load(&mut h.app); + } else { + h.app.render_workspace.view.method = method; + } + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + let before = h.app.session.doc.clone(); + let revision = h.app.session.revision; + h.frames(3); + for section in ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(section))).is_some()); + } + let reason = match method { + ImageMethod::Raster => "render.method_limit_raster", + ImageMethod::CpuRaytrace => "render.lighting_samples_need_area", + ImageMethod::GpuRaytrace => "render.light_gpu_punctual", + }; + assert!(crate::scenario::rect_of(&format!("dialog:note:{reason}")).is_some()); + if method == ImageMethod::GpuRaytrace { + assert!(crate::scenario::rect_of("dialog:note:render.lighting_shadow_cpu").is_some()); + assert!(crate::scenario::rect_of("dialog:note:render.lighting_samples_cpu").is_some()); + } + assert!(h.widget(h.app.tr("render.lighting_budget_help")).is_some()); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.session.revision, revision); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn render_assign_gestures_stage_tools_and_selection_actions_use_commands() { + let (mut h, _) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + assert!(crate::workspace::destination(solidcraft_engine::find_command(id).unwrap()).is_none()); + } + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!(pill.width() < 200.0, "{pill:?}"); + for index in 0..4 { + assert!(pill.contains_rect(crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap())); + } + h.step(&json!({"click":{"handle":"render:stage:appearance.pick_up"}})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"handle":"selection:action:0"}})).unwrap(); + assert!(crate::scenario::rect_of("render:look_chain").is_some()); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), 1); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert!(h.app.preferences.render_library_favorites.is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"selection:action:1"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"dialog:Replace with"}})).unwrap(); + h.step(&json!({"widget":"Copper"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "Copper"); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"selection:action:3"}})).unwrap(); + assert!(!h.app.session.body_visible("Plate")); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:selection").is_none()); + assert!(crate::scenario::rect_of("render:stage:appearance.paint").is_none()); +} + +#[test] +fn render_assign_gestures_replacement_draft_cannot_cross_a_document_edit() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.app.start("appearance.replace"); + assert!(assign::replacement_open(&h.app)); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Red"})).unwrap(); + h.frames(3); + assert!(!assign::replacement_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); +} + +#[test] +fn render_assign_gestures_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.cylinder", json!({"body_name":"Boss","radius":10,"height":20})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Boss"],"appearance":"Aluminum - Anodized Blue"})).unwrap(); + h.app.run("solid.sphere", json!({"body_name":"Knob","center":[0,0,28],"radius":8})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Knob"],"appearance":"Copper"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + h.app.pending_fit = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..48 { + crate::scenario::clear_handles(); + let events = h + .app + .viewport + .rect + .and_then(|rect| crate::viewport::projection(&h.app, rect).to_screen(solidcraft_engine::geom::Vec3::new(0.0, 0.0, 28.0))) + .filter(|_| frame == 1) + .map(|at| vec![egui::Event::PointerMoved(at)]) + .unwrap_or_default(); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), time: Some(frame as f64 / 60.0), events, ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 47 { + assert!( + crate::scenario::rect_of("kit:tooltip").is_some(), + "the model hover uses the standard kit tooltip; hover: {:?}, pointer: {:?}", + h.app.viewport.hover, + ctx.pointer_hover_pos() + ); + let tooltip = crate::scenario::rect_of("kit:tooltip").unwrap(); + assert!(tooltip.distance_to_pos(ctx.pointer_hover_pos().unwrap()) < Tokens::get().control_height, "{tooltip:?}"); + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!((150.0..170.0).contains(&pill.width()), "{pill:?}"); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_GESTURES_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("look-controls-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_lights_each_kind_contains_design_sections_and_real_parameter_fields_in_order() { + for (method, kind) in + [("cpu_raytrace", "area"), ("cpu_raytrace", "point"), ("cpu_raytrace", "directional"), ("gpu_path", "area"), ("gpu_path", "directional")] + { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + let options = if method == "gpu_path" { json!({"lighting":{}}) } else { json!({"lights":[],"punctual_lights":[],"area_lights":[]}) }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":method,"options":options}}})).unwrap(); + setups::load(&mut h.app); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":kind}))).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let before = h.app.session.doc.clone(); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + let mut sections = vec!["render.light_position"]; + if kind == "area" { + sections.push("render.lighting_shape"); + } + if kind == "point" { + sections.push("render.lighting_falloff"); + } + sections.push("render.light_behaviour"); + let rects: Vec<_> = sections.iter().map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()).collect(); + assert!(rects.windows(2).all(|pair| pair[0].bottom() <= pair[1].top()), "{method}/{kind}"); + let fields: &[&str] = match kind { + "area" => &["width_mm", "height_mm", "radiance:0", "edge_u_mm:0", "edge_v_mm:0", "position_mm:0"], + "point" => &["reference_distance_mm", "minimum_distance_mm", "position_mm:0"], + _ => &["direction:0", "direction:1", "direction:2"], + }; + for field in fields { + assert!(crate::scenario::rect_of(&format!("render:light:{field}")).is_some(), "{method}/{kind}: {field}"); + } + for key in ["render.lighting_solo", "render.lighting_mute", "render.light_duplicate", "render.light_delete"] { + assert!(h.widget(h.app.tr(key)).is_some(), "{method}/{kind}: {key}"); + } + assert!(crate::scenario::rect_of("dialog:note:render.light_place_pending").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn render_lighting_preset_materialises_values_and_replacement_requires_review_consent() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + // Confirm's primary action is disabled until its explicit acknowledgement. + h.step(&json!({"widget":h.app.tr("render.lighting_consent")})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_apply")})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_some()); + assert!(h.app.render_workspace.view.raytrace.lights.is_none()); + let lights = light::rows(&h.app).unwrap(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:lighting:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.lights.as_ref().unwrap().len(), lights.len()); + let materialised = light::rows(&h.app).unwrap(); + for (before, after) in lights.iter().zip(materialised) { + assert_eq!(before.colour, after.colour); + assert_eq!(before.intensity, after.intensity); + } + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); +} + +#[test] +fn render_lighting_hostile_numeric_edits_refuse_without_panics_or_partial_state() { + let mut h = render_lights_fixture(); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":"point"}))).unwrap(); + let before = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + for set in + [json!({"reference_distance_mm":1e300}), json!({"minimum_distance_mm":-1}), json!({"position_mm":[1e300,0,0]}), json!({"direction":[0,0,0]})] + { + assert!(light::edit(&mut h.app, "render.lights.set", Some("point:0"), Some(set)).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + } + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_shadow_edits_are_undoable_and_preset_reviews_reject_changed_drafts() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.lighting_shadows")})).unwrap(); + assert!(!h.app.render_workspace.view.raytrace.shadows); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(matches!(&h.app.session.doc.render.setups["Studio"].job, + Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options }) if !options.shadows)); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, before); + h.frames(3); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_some()); + h.app.render_workspace.view.draft.width = 1200; + h.frames(3); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_none()); + assert_eq!(h.app.session.doc, before); + assert_eq!(h.app.render_workspace.view.draft.width, 1200); +} + +#[test] +fn geometry_budget_follows_the_device_buffer_limit_and_keeps_the_web_cap() { + // The standard 256 MiB device buffers: 2 GiB, far past the old fixed 128 MiB. + assert_eq!(geometry_budget(256 << 20, false), 2 << 30); + assert!(admit_geometry(129 << 20, geometry_budget(256 << 20, false)).is_ok()); + // A smaller device gets less, a larger one no more than the ceiling. + assert_eq!(geometry_budget(64 << 20, false), 512 << 20); + assert_eq!(geometry_budget(u64::MAX, false), DESKTOP_GEOMETRY_CEILING); + for device in [0, 256 << 20, u64::MAX] { + let budget = geometry_budget(device, true); + assert_eq!(budget, 128 << 20); + assert!(admit_geometry(budget, budget).is_ok()); + assert!(admit_geometry(budget + 1, budget).is_err()); + } +} + +#[test] +fn geometry_refusal_reports_scene_size_limit_and_recovery() { + use solidcraft_engine::{ + geom::{Aabb3, Mesh}, + render::ProductMesh, + }; + let scene = ProductScene { + meshes: vec![ProductMesh { + name: "Synthetic assembly".into(), + mesh: Arc::new(Mesh { triangles: vec![[0; 3]; 1 << 20], ..Default::default() }), + color: [128; 3], + opacity: 1.0, + surface: Some( + solidcraft_engine::render::surface::OpaqueSurface::new(solidcraft_engine::geom::Vec3::new(0.5, 0.5, 0.5), 0.0, 0.5, 1.5).unwrap(), + ), + transmission: None, + faces: Vec::new(), + }], + bounds: Aabb3::EMPTY, + }; + let error = gpu_scene_with_budget(&scene, WEB_GEOMETRY_BYTES).err().unwrap(); + assert!(error.contains("144.0 MiB"), "{error}"); + assert!(error.contains("128.0 MiB"), "{error}"); + assert!(error.contains("Hide bodies in Design"), "{error}"); + let refused = upload_refusal(144 << 20, "Out of Memory"); + assert!(refused.contains("144.0 MiB") && refused.contains("Out of Memory") && refused.contains("Hide bodies in Design"), "{refused}"); +} + +#[test] +fn previous_geometry_budget_restores_the_fixed_limit() { + for web in [false, true] { + for device in [64 << 20, 256 << 20, u64::MAX] { + let device_budget = geometry_budget(device, web); + assert_eq!(preferred_geometry_budget(device_budget, false), device_budget); + let previous = preferred_geometry_budget(device_budget, true); + assert_eq!(previous, MAX_GEOMETRY_BYTES as u64); + assert!(admit_geometry(previous, previous).is_ok()); + assert!(admit_geometry(previous + 1, previous).is_err()); + } + } +} + +#[test] +fn geometry_budget_change_retries_cached_admission_without_document_changes() { + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let bytes = preview_upload_plan(&scene, usize::MAX).unwrap().bytes().unwrap() as u64; + let mut state = State::default(); + assert!(state.prepare_preview((7, 123, 99, bytes - 1), || Ok(scene.clone())).is_err()); + state.prepare_preview((7, 123, 99, bytes), || Ok(scene)).unwrap(); + assert_eq!(state.preview_upload_bytes, Some(bytes as usize)); + assert!(state.scene_error.is_none()); +} + +#[test] +fn cpu_interactive_cold_assembly_binding_refuses_without_preparing_world() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.session.execute("component.create", &json!({"name":"Part","grounded":false})).unwrap(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let initial = h.app.session.world_state(); + let name = initial.bodies[0].name.clone(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + // Exact placement metadata changes without running a UI paint or world query. + let occurrence: u64 = serde_json::from_value(component["occurrence"].clone()).unwrap(); + h.app.session.pending_moves.insert(occurrence, solidcraft_engine::doc::IDENTITY); + assert!(h.app.session.interactive_cached_world_state().is_none()); + let model = h.app.session.model.state(); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(h.app.session.interactive_cached_world_state().is_none(), "binding proof must not prepare cold placements"); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + cpu::set_reflection(&mut h.app, &name, None).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(h.app.session.interactive_cached_world_state().is_none(), "empty reflections need no prepared world"); +} + +#[test] +fn interactive_egui_clock_is_finite_monotonic_and_requires_no_platform_instant() { + use std::time::Duration; + let mark = Duration::from_secs(2); + for time in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1.0, f64::MAX] { + assert_eq!(interactive::monotonic(mark, time), mark); + } + assert_eq!(interactive::monotonic(mark, 3.5), Duration::from_millis(3500)); +} + +fn interactive_control_frame(h: &mut Harness, time: f64, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + events, + ..Default::default() + }, + |ui| { + ui.set_width(300.0); + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +#[test] +fn interactive_is_opt_in_and_refuses_raster_or_cooperative_hosts_without_fallback() { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + let document = h.app.session.doc.clone(); + let path = matches!(h.app.render_workspace.path_host, PathHost::NotStarted); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted), path); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_ui_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":8,"height":4,"body_name":"Subject"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host)).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + // Do not enter through a deferred GPU factory in CPU-only adapter tests. + h.app.ui.tab = "RENDER".into(); + h +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_test_cpu_branch(h: &mut Harness, case: &str) -> bool { + let host = h.app.session.render_job_host().unwrap(); + let supported = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + if supported { + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=true"); + return true; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + false +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_runtime_builder_preserves_hdr_ev_and_muted_lights_without_final_dimension_admission() { + let mut h = interactive_ui_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"cpu_raytrace"}}})).unwrap(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.raytrace.shadows = false; + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let before = h.app.session.doc.clone(); + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["width"], 3840, "engine must fit before admission"); + assert!(wire["settings"]["job"].is_null()); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.5); + assert_eq!(wire["raytrace"]["shadows"], false); + assert_eq!(wire["raytrace"]["lights"][0]["intensity"], 0.0); + assert_eq!(wire["environment"]["resource"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert!(wire["environment"].get("path").is_none()); + assert!(raw_image_request(&h.app).is_err(), "final admission must remain unchanged"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_control_frame(&mut h, 0.0, vec![]); + let first = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_control_frame(&mut h, 0.5, vec![]); + let camera = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(camera > first); + h.app.render_workspace.view.raytrace.shadows = false; + interactive_control_frame(&mut h, 1.0, vec![]); + let transport = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(transport > camera); + h.app.session.visibility.hidden_bodies.push("Subject".into()); + interactive_control_frame(&mut h, 1.5, vec![]); + let visibility = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(visibility > transport); + assert_eq!(h.app.session.revision, revision, "all three edits deliberately bypass CAD revision"); + assert_eq!(interactive::inspect(&h.app)["pending_capture"], false, "before_paint never dispatches a worker"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots") { + return; + } + interactive_control_frame(&mut h, 0.0, vec![]); + let mut time = 0.01; + for action in ["on", "pause", "resume", "off"] { + let rect = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + let at = rect.center(); + interactive_control_frame( + &mut h, + time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + ], + ); + time += 0.01; + interactive_control_frame(&mut h, time, vec![]); + time += 0.01; + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + enter(&mut h.app, false).unwrap(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); +} + +#[test] +fn interactive_reset_retains_one_real_receiver_and_discards_its_late_foreign_error() { + use solidcraft_engine::render::job::interactive::{Interactive, VisualRevision}; + use std::{sync::mpsc, time::Duration}; + let mut h = Harness::new(); + let mut controller = Interactive::new(7001); + controller.enable(VisualRevision { scene_generation: 0, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = controller.capture(Duration::from_millis(200)).unwrap().unwrap(); + let (sender, receiver) = mpsc::channel(); + h.app.render_workspace.interactive.pending = Some(interactive::Pending { uid: h.app.session.uid, ticket, receiver }); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending()); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending(), "a second document reset cannot orphan the pending worker"); + sender.send(Err("late old capture".into())).unwrap(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(interactive::inspect(&h.app)["error"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_background_final_metadata_suspends_without_cancelling_queued_final() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_background_final_metadata_suspends_without_cancelling_queued_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + let job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + serde_json::from_value::(reply["job"].clone()).unwrap() + }; + let retained = host.admitted_bytes(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + let background = h.app.docs.background().next().unwrap(); + assert_eq!(background.render_job_handle(job).unwrap().status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert_eq!(host.admitted_bytes(), retained); + assert!(!h.app.render_workspace.interactive.pending()); +} + +// Native CPU acceptance of the real M3 dispatcher; no native window or GPU. +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveHeldCallback { + job: solidcraft_engine::render::job::JobHandle, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool, paint: bool) -> (egui::FullOutput, bool) { + let mut painted = false; + let output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + ..Default::default() + }, + |ui| { + // tick dispatches through the actual production spawn(Snapshot) path. + // Do not run a second refresh here: the callback must be held before UI delivery. + if dispatch { + interactive::tick(&mut h.app, ui.ctx()); + } else { + interactive::before_paint(&mut h.app, ui.ctx()); + } + if paint { + painted = interactive::paint(&h.app, ui, ui.max_rect()); + } + }, + ); + (output, painted) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_clear_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool) { + let (mut output, painted) = interactive_acceptance_frame(h, time, dispatch, false); + assert!(!painted); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_hold_real_completed_callback(h: &mut Harness) -> InteractiveHeldCallback { + use solidcraft_engine::render::job::Phase; + use std::{sync::mpsc, time::Duration}; + // The actual capture thread owns and invokes the real engine Snapshot.run. + // This test only withholds its actual returned message from the UI consumer. + // No tick/paint is called while the receiver is temporarily removed. + let mut pending = h.app.render_workspace.interactive.pending.take().expect("production tick must start a capture"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("real snapshot worker did not return"); + assert!(matches!(&reply, Ok(true)), "real snapshot must be adopted: {reply:?}"); + let job = + interactive::test_current(&h.app).expect("Interactive controller access must succeed").expect("Snapshot.run must attach the real CPU job"); + assert_eq!(job.id(), pending.ticket.job_id()); + assert_eq!(pending.uid, h.app.session.uid); + let status = job.wait_timeout(Duration::from_secs(60)).expect("real CPU job did not finish"); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(status.error.is_none()); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive.unwrap().samples_per_pixel, 16); + assert_eq!((status.request.width, status.request.height), (16, 16)); + let frame = job.frame().unwrap().expect("Completed requires real frame bytes"); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert_eq!(frame.info.job, job.id()); + assert_eq!(frame.info.scene_generation, pending.ticket.revision().scene_generation); + assert!(!frame.png().is_empty()); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + { + use sha2::{Digest, Sha256}; + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + } + assert!(job.preview().unwrap().is_none(), "terminal image is distinct from the intermediate preview slot"); + // The renderer's Completed progress is normalized to 1/1, not an SPP counter. + assert_eq!((status.progress.done, status.progress.total), (1, 1)); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveHeldCallback { job, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_assert_final_export_isolation(h: &mut Harness, job: &solidcraft_engine::render::job::JobHandle) { + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.render_workspace.image.is_none()); + assert!(!studio::linear_export_available(&h.app)); + let registry_error = h.app.session.render_job_handle(job.id()).err().expect("preview must not enter the final registry"); + assert!(registry_error.to_string().contains("WrongOwner"), "{registry_error}"); + let path = h.dir.join(format!("interactive-not-exportable-{}-{}.png", job.id().session, job.id().serial)); + assert!(!path.exists()); + let error = h.app.session.execute("render.export", &json!({"job":job.id(),"path":path,"format":"png"})).unwrap_err(); + // Require the actual preview/final ownership guard, rather than accepting a + // path/format/refusal error which would not prove final-registry isolation. + assert!(error.to_string().contains("WrongOwner"), "{error}"); + assert!(!path.exists()); + assert!(job.frame().unwrap().is_some(), "export refusal must not consume preview pixels"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported") { + return; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + assert!(!h.app.render_workspace.interactive.pending()); + // Explicit egui time relative to the inherited clock crosses the 200 ms group; + // this does not wait on wall time or sleep to make a race likely. + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(interactive::test_cache(&h.app).is_none(), "worker completion alone must not fabricate a UI cache"); + let frame = held.job.frame().unwrap().unwrap(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + assert!(!h.app.render_workspace.interactive.pending()); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.job, held.job.id()); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!(samples, 16); + assert!(complete, "completed16 must use the completed key, still only in the provisional UI cache"); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + let uploaded = &output.textures_delta.set.get(&texture).expect("first real PNG publication must upload a texture").first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty())) + ); + let (mut repaint, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + assert!(!repaint.textures_delta.set.contains_key(&texture), "unchanged JobId/sequence/revision must reuse its texture"); + repaint.textures_delta.clear(); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending(), "Off retains the single undrained receiver"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 1.0, true); + let pending = h.app.render_workspace.interactive.pending.as_ref().unwrap(); + assert_eq!(pending.ticket.job_id(), held.job.id(), "reactivation cannot replace an undrained capture"); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 1.1, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(!painted, "Pause may retain already displayed pixels, but cannot adopt this unseen callback"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let old = held.job.id(); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert_eq!(h.app.session.revision, revision); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + let newer = interactive_hold_real_completed_callback(&mut h); + assert_ne!(newer.job.id(), old); + newer.sender.send(newer.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, newer.job.id()); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &newer.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveRecoveryReply { + id: solidcraft_engine::render::job::JobId, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_hold_reply(h: &mut Harness) -> InteractiveRecoveryReply { + use std::{sync::mpsc, time::Duration}; + let mut pending = h.app.render_workspace.interactive.pending.take().expect("actual tick must dispatch a Snapshot"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("actual capture worker did not return"); + let id = pending.ticket.job_id(); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveRecoveryReply { id, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_missing_hdr(h: &mut Harness) -> (std::path::PathBuf, Vec) { + let path = h.dir.join("interactive-recovery-original.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert!(interactive_request(&h.app).is_ok(), "valid inspected metadata must reach actual worker preparation"); + std::fs::remove_file(&path).unwrap(); + (path, bytes) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_error(h: &mut Harness, time: f64) -> serde_json::Value { + interactive_clear_acceptance_frame(h, time, true); + let status = interactive::inspect(&h.app); + assert_eq!(status["phase"], "Error"); + assert!(status["error"].as_str().is_some_and(|error| !error.is_empty())); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + status["error"].clone() +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_success(h: &mut Harness, dispatch_time: f64, paint_time: f64) -> solidcraft_engine::render::job::JobId { + interactive_clear_acceptance_frame(h, dispatch_time, true); + let held = interactive_hold_real_completed_callback(h); + let id = held.job.id(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(h, paint_time, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, id); + interactive_assert_final_export_isolation(h, &held.job); + id +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover") { + return; + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 2.0), error); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 2.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_recovery_require_success(&mut h, epoch + 2.301, epoch + 2.4); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit() { + for recovery in ["resume", "edit"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let request = interactive_request(&h.app).unwrap(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.as_ref().is_err_and(|error| !error.is_empty()), "missing HDR must fail actual preparation: {:?}", failed.reply); + assert!( + interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none(), + "preparation failure is not an admitted job-status failure" + ); + let failed_id = failed.id; + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + for offset in [0.6, 1.0] { + assert_eq!(interactive_recovery_require_error(&mut h, epoch + offset), error, "unchanged input must not retry"); + } + if recovery == "resume" { + std::fs::write(&path, bytes).unwrap(); + assert_eq!(interactive_request(&h.app).unwrap(), request, "repairing external bytes is not a UI intent edit"); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.1), error, "file repair alone cannot silently resume"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } else { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + } + let new_id = interactive_recovery_require_success(&mut h, epoch + 1.301, epoch + 1.4); + assert_ne!(new_id, failed_id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_user_pause_survives_error_fixing_edit_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_user_pause_survives_error_fixing_edit_until_explicit_resume") { + return; + } + let _ = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + interactive_recovery_require_error(&mut h, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.4, false); + interactive_clear_acceptance_frame(&mut h, epoch + 2.0, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 2.201, epoch + 2.3); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(held.reply.unwrap(), "native Snapshot/CPU work really finished before transport failure"); + // Deliberately close the actual std channel instead of fabricating an Err. + // This covers consumer Disconnected, not a claim that the native worker crashed. + drop(held.sender); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert_eq!(error, h.app.tr("render.interactive_error")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent() { + for recovery in ["edit", "resume"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + if recovery == "edit" { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + } else { + std::fs::write(path, bytes).unwrap(); + // First consume clock input without consuming the still-held reply. + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + assert_eq!( + h.app.render_workspace.interactive.pending.as_ref().unwrap().ticket.job_id(), + failed.id, + "one old receiver still blocks new dispatch" + ); + failed.sender.send(failed.reply).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.6, false); + assert!(interactive::inspect(&h.app)["error"].is_null(), "actual old failure must be discarded"); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + let new_id = interactive_recovery_require_success(&mut h, epoch + 0.7, epoch + 0.8); + assert_ne!(new_id, failed.id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.4), error); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).unwrap_err().contains(h.app.tr("render.interactive_final_active"))); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + // Only the test's explicit owner cancellation ends its queued final. + final_job.cancel().unwrap(); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.5), error); + std::fs::write(path, bytes).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.701, epoch + 0.8); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Cancelled); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_actual_png_display_cap_error_latches_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_actual_png_display_cap_error_latches_until_explicit_resume") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + held.sender.send(held.reply).unwrap(); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.3), + ..Default::default() + }, + |ui| { + // Real decoder admission against an invalid display capability; retain + // the real CPU PNG and restore input before fonts/end-frame processing. + let previous = ui.ctx().input(|input| input.max_texture_side); + ui.ctx().input_mut(|input| input.max_texture_side = 0); + interactive::before_paint(&mut h.app, ui.ctx()); + ui.ctx().input_mut(|input| input.max_texture_side = previous); + assert!(!interactive::paint(&h.app, ui, ui.max_rect())); + }, + ); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.4); + assert_eq!(error, h.app.tr("render.error_display_dimensions")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error, "restoring display cap alone cannot rearm capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4), + ..Default::default() + }, + |ui| { + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + assert!(text.contains("16 × 16 px"), "actual cached dimensions must be visible: {text}"); + assert!(!text.contains("3840 × 2160 px"), "final draft cannot relabel the captured preview"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + let (info, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((info.width, info.height, samples, complete), (16, 16, 16, true)); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_card_bounds_avoid_current_selection_docks_and_navigation_at_wide_and_narrow_sizes() { + for (width, height) in [(1600.0, 1000.0), (760.0, 700.0)] { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.shell.workspace_panels.clear(); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let content = egui::Rect::from_min_max(egui::pos2(0.0, 132.0), egui::pos2(width, height - 56.0)); + let left = egui::Rect::from_min_max(egui::pos2(8.0, 140.0), egui::pos2(274.0, height - 64.0)); + let right = egui::Rect::from_min_max(egui::pos2(width - 313.0, 140.0), egui::pos2(width - 8.0, height - 64.0)); + crate::shell::register_panel(&mut h.app, "render:browser", Some(left), Some(crate::ui_kit::Edge::Left)); + crate::shell::register_panel(&mut h.app, "render:inspector", Some(right), Some(crate::ui_kit::Edge::Right)); + let centre = (left.right() + right.left()) / 2.0; + let navigation = egui::Rect::from_center_size(egui::pos2(centre, content.bottom() - 28.0), egui::vec2(120.0, 40.0)); + let axis = egui::Rect::from_min_size(egui::pos2(right.left() - 110.0, content.top()), egui::vec2(110.0, 110.0)); + h.app.viewport.layout = + Some(crate::viewport_layout::Layout { viewport, drawable: content, content, axis_view: axis, navigation, confirm: egui::Rect::NOTHING }); + // A new measured selection replaces the old one in this very frame. + // Both positions cut across the old top-centre status/action region. + for y in [content.top() + 90.0, content.top() + 180.0] { + let selection = egui::Rect::from_center_size(egui::pos2(centre, y), egui::vec2(180.0, 34.0)); + crate::shell::register_panel(&mut h.app, "render:selection", Some(selection), None); + let available = interactive::overlay_bounds(&h.app, content); + assert!(available.is_positive(), "{width}: no space for the Interactive card"); + assert!(content.contains_rect(available), "{width}: {available:?} outside {content:?}"); + for occupied in [selection, left, right, navigation, axis] { + assert!(!available.intersect(occupied).is_positive(), "{width}: {available:?} overlaps {occupied:?}"); + } + assert!(available.width() >= Tokens::get().control_height + Tokens::get().space_8); + } + assert!(!interactive::overlay_bounds(&h.app, egui::Rect::NOTHING).is_positive()); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0, left); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0, right); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_overlay_keeps_real_selection_actions_and_pause_off_targets_accessible_without_dispatch() { + fn overlay_frame(h: &mut Harness, size: egui::Vec2, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, + |ui| { + // The shell clears Render reservations at the start of a real frame. + // Keep the already measured docks but never leave a previous selection + // rectangle that could make the moved-call regression pass by accident. + h.app.shell.workspace_panels.remove("render:selection"); + crate::render_ui::overlays(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); + } + for size in [egui::vec2(1600.0, 1000.0), egui::vec2(760.0, 700.0)] { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_overlay_selection_controls") { + return; + } + h.call("ui.resize", json!({"width":size.x as u32,"height":size.y as u32})); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Subject".into()}]})).unwrap(); + h.frames(4); + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let selection_before = crate::scenario::rect_of("render:selection").unwrap(); + let actions_before: Vec<_> = (0..4).map(|index| crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap()).collect(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let docks = h.app.shell.workspace_panels.clone(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Paint the production overlays, but never tick or run a Snapshot worker. + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let card = crate::scenario::rect_of("render:interactive-card").unwrap(); + let selection = crate::scenario::rect_of("render:selection").unwrap(); + assert_eq!(selection, selection_before, "our card must not move the author's toolbar"); + assert!(!card.intersect(selection).is_positive()); + let content = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + assert!(content.contains_rect(card), "{size:?}: {card:?} outside {content:?}"); + for (index, before) in actions_before.iter().enumerate() { + let action = crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap(); + assert_eq!(&action, before); + assert!(selection.contains_rect(action)); + assert!(!card.intersect(action).is_positive(), "author action {index} is occluded"); + } + for action in ["pause", "off"] { + let target = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + assert!(card.contains_rect(target), "{size:?}: {action} clipped outside {card:?}: {target:?}"); + assert!(!selection.intersect(target).is_positive()); + } + for action in ["pause", "off"] { + let at = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap().center(); + for pressed in [true, false] { + overlay_frame( + &mut h, + size, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + overlay_frame(&mut h, size, vec![]); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert!(!h.app.render_workspace.interactive.pending()); + } + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + for id in ["render:browser", "render:inspector", "render:appearances", "render:shots_strip"] { + let current = h.app.shell.workspace_panels.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + let before = docks.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + assert_eq!(current, before, "{id}"); + } + // With Interactive Off, the author's real hit target still dispatches. + let favorite_count = h.app.preferences.render_library_favorites.len(); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), favorite_count + 1); + assert_eq!(crate::scenario::rect_of("render:selection").unwrap(), selection_before); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_waiting_show_text(h: &mut Harness, time: f64) -> String { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(time), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + output.textures_delta.clear(); + text +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "the fallback refusal is the real no-GPU positive control"); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + let fallback = h.app.tr("render.error_gpu_preview").to_string(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.01).contains(&fallback)); + + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let waiting = interactive_waiting_show_text(&mut h, epoch + 0.02); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!waiting.contains(&fallback), "real show must not enter the model-preview refusal while waiting"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "show/before_paint must not dispatch"); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.025, false, true); + assert!(!painted, "reserving the canvas does not claim an image was painted"); + output.textures_delta.clear(); + + h.app.render_workspace.view.result = true; + assert!(!interactive::awaiting_current_frame(&h.app), "the result view keeps priority"); + h.app.render_workspace.view.result = false; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.ui.tab = "MODEL".into(); + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.ui.tab = "RENDER".into(); + + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.03).contains(&fallback), "pause before any image keeps its existing fallback"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + assert!(!interactive_waiting_show_text(&mut h, epoch + 0.04).contains(&fallback)); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let error = interactive_waiting_show_text(&mut h, epoch + 0.05); + assert_eq!(interactive::inspect(&h.app)["phase"], "Error"); + assert!(!interactive::inspect(&h.app)["error"].is_null()); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(error.contains(&fallback), "an input error keeps the existing model-preview route"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.06).contains(&fallback)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let old = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + assert!(!interactive::awaiting_current_frame(&h.app)); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let document = h.app.session.doc.clone(); + + h.app.render_workspace.view.raytrace.shadows = false; + let text = interactive_waiting_show_text(&mut h, epoch + 0.4); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_cache(&h.app).is_none(), "the previously accepted image must be dropped"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.41, false, true); + assert!(!painted, "old pixels cannot become current while the new request waits"); + output.textures_delta.clear(); + + let new = interactive_recovery_require_success(&mut h, epoch + 0.901, epoch + 1.0); + assert_ne!(new, old); + assert!(!interactive::awaiting_current_frame(&h.app)); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), new); + assert!(!job.status().unwrap().request.raytrace.as_ref().unwrap().shadows); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "presentation and runtime settings do not author CAD state"); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let (before, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.shadows = false; + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted, "explicit pause still permits the already displayed image"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app)); + let (after, after_samples, after_complete, after_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((after.job, after.png_sha256), (before.job, before.png_sha256)); + assert_eq!((after_samples, after_complete, after_texture), (samples, complete, texture)); + + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let text = interactive_waiting_show_text(&mut h, epoch + 0.5); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.51, false, true); + assert!(!painted); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.cam.yaw += 0.2; + let text = interactive_waiting_show_text(&mut h, epoch + 0.3); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::awaiting_current_frame(&h.app)); + interactive_assert_final_export_isolation(&mut h, &held.job); + + let old_uid = h.app.session.uid; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_ne!(h.app.session.uid, old_uid); + assert!(!interactive::awaiting_current_frame(&h.app), "a foreign context cannot reserve the canvas even before refresh"); + h.app.ui.tab = "RENDER".into(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.5, false); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(!painted, "neither the old image nor its waiting presentation belongs to another document"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::awaiting_current_frame(&h.app)); + let before = interactive::inspect(&h.app); + assert_eq!(before["enabled"], true); + assert_eq!(before["phase"], "Updating"); + assert_eq!(before["paused"], false); + assert!(before["error"].is_null()); + assert!(!h.app.render_workspace.view.result); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + + let uid = h.app.session.uid; + let document = h.app.session.doc.clone(); + let mut foreign = Session::new((*document).clone()); + assert_ne!(foreign.uid, uid); + // Use real engine Sessions and the same ownership swap as documents::swap_in. + // Deliberately omit the UI reset: it would otherwise mask is_current's guard. + // Retain the original Session so its registry/controller lifetime stays live. + std::mem::swap(&mut h.app.session, &mut foreign); + assert_ne!(h.app.session.uid, uid); + assert_eq!(h.app.session.doc, document, "equal design contents do not confer session ownership"); + assert_eq!(interactive::inspect(&h.app), before, "the context is still enabled, not reset or refreshed"); + assert!(active(&h.app)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(!h.app.render_workspace.view.result); + assert!(!interactive::awaiting_current_frame(&h.app), "a live context owned by another Session cannot reserve the canvas"); + assert_eq!(interactive::inspect(&h.app), before, "the predicate must remain read-only"); + + std::mem::swap(&mut h.app.session, &mut foreign); + assert_eq!(h.app.session.uid, uid); + assert_eq!(interactive::inspect(&h.app), before); + assert!(interactive::awaiting_current_frame(&h.app), "restoring the real owner proves the same context remained live"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!h.app.render_workspace.interactive.pending()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_frame(h: &mut Harness, time: &mut f64, events: Vec) { + *time += 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_fixture(case: &str) -> Option<(Harness, f64, egui::Pos2)> { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, case) { + return None; + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + h.app.preferences.nav = "fusion".into(); + h.app.preferences.zoom_to_cursor = false; + h.app.preferences.smooth_wheel_zoom = false; + let mut time = interactive::test_clock(&h.app).as_secs_f64(); + for _ in 0..3 { + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + } + let rect = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, rect); + let at = projection.to_screen(h.app.cam.target).unwrap(); + assert!(!crate::shell::covered(&h.app, at)); + assert!( + crate::viewport::pick(&h.app, &projection, at).iter().any(|hit| matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject")) + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + Some((h, time, at)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_click(h: &mut Harness, time: &mut f64, at: egui::Pos2, button: egui::PointerButton, mods: egui::Modifiers) { + interactive_canvas_input_frame(h, time, vec![egui::Event::ModifiersChanged(mods), egui::Event::PointerMoved(at)]); + for pressed in [true, false] { + interactive_canvas_input_frame(h, time, vec![egui::Event::PointerButton { pos: at, button, pressed, modifiers: mods }]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none(), "hidden geometry cannot advertise a hover target"); + assert!(h.app.session.selection.is_empty(), "plain/add/toggle clicks cannot select invisible geometry"); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none(), "a right click cannot open a menu for hidden geometry"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending(), "show never dispatches a capture"); + + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_some(), "the same real hit remains available with Interactive Off"); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_some(), "the same native canvas click still opens the normal body menu"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work() { + for sampling in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work") + else { + return; + }; + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let look = h.app.render_workspace.view.assign.look.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.assign.look, look, "no hidden face is sampled"); + assert_eq!(h.app.render_workspace.view.assign.sampling, sampling); + assert_eq!(h.app.render_workspace.view.assign.painting, !sampling); + + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + if sampling { + assert!(!h.app.render_workspace.view.assign.sampling); + assert!(h.app.render_workspace.view.assign.painting, "Off permits real sampling to arm paint"); + } else { + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target") + else { + return; + }; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "positive control: real Off drag reached geometry"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_current_and_paused_images_keep_canvas_paint_and_final_observation() { + for paused in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_current_and_paused_images_keep_canvas_paint_and_final_observation") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + if paused { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + let undo = h.app.session.undo.len(); + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + if paused { + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::awaiting_current_frame(&h.app)); + } else { + assert!(interactive::test_cache(&h.app).is_none(), "the final observation sees the appearance edit made by this canvas click"); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + assert!(interactive::test_cache(&h.app).is_some(), "before show, old UI state has not yet observed the visible setting edit"); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.session.selection.is_empty(), "the release cannot pick using the previous frame's cache/phase"); + assert!(h.app.viewport.hover.is_none()); + + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, 3.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert_ne!(h.app.cam, camera, "the waiting guard must not swallow real shared camera navigation"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "neither observation dispatches Snapshot"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(accepted.job, job); + assert_eq!((samples, complete), (16, true)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(!h.app.render_workspace.interactive.pending()); + + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let selection = h.app.session.selection.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "the real drag must start over the accepted CPU image"); + assert!(assign::hover(&h.app).is_some()); + let (pressed, pressed_samples, pressed_complete, pressed_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((pressed.job, &pressed.png_sha256), (job, &accepted.png_sha256)); + assert_eq!((pressed_samples, pressed_complete, pressed_texture), (samples, complete, texture)); + assert!(!interactive::awaiting_current_frame(&h.app)); + + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + // No tick, show, refresh, move or other UI frame between this edit and release. + // The old image/drag are still present, so only same-frame observation can reject the drop. + let (before_release, _, _, before_release_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((before_release.job, &before_release.png_sha256, before_release_texture), (job, &accepted.png_sha256, texture)); + assert!(assign::preview(&h.app).is_some()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert_eq!(h.app.session.selection, selection); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch Snapshot to consume this release"); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "show must not attach a replacement CPU job"); + assert!(active(&h.app)); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(!assign::cancel(&mut h.app), "the release must consume the drag; nothing may remain for Escape to cancel"); + + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert_eq!(h.app.session.selection, selection, "blank-canvas clicks cannot clear, add to or toggle the existing selection"); + assert!(h.app.viewport.hover.is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn gpu_failed_host_keeps_specific_reason_in_image_params_and_disabled_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for reason in ["This Direct3D 12 session has not tested Vulkan.", "Vulkan device creation failed: deliberate independent diagnostic 47."] { + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_ne!(reason, h.app.tr("render.gpu_unavailable")); + assert_eq!(image_params(&h.app).unwrap_err(), reason); + for id in ["render.preflight", "render.start"] { + let command = solidcraft_engine::find_command(id).unwrap(); + assert!(command.info(&h.app.session).enabled, "the engine must not hide the UI readiness check"); + let info = interactive_command_info(&h.app, command); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(reason), "{id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn gpu_pending_hosts_keep_generic_disabled_reason_without_starting_setup() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let generic = h.app.tr("render.gpu_unavailable").to_string(); + // This channel represents a still-pending answer; no worker or GPU factory is created. + let (_sender, receiver) = std::sync::mpsc::channel(); + for host in [PathHost::NotStarted, PathHost::Preparing(receiver, std::time::Instant::now())] { + let preparing = matches!(&host, PathHost::Preparing(..)); + h.app.render_workspace.path_host = host; + assert_eq!(image_params(&h.app).unwrap_err(), generic); + for id in ["render.preflight", "render.start"] { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(generic.as_str()), "{id}"); + } + assert_eq!(matches!(&h.app.render_workspace.path_host, PathHost::Preparing(..)), preparing); + assert!(matches!(&h.app.render_workspace.path_host, PathHost::NotStarted | PathHost::Preparing(..))); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn gpu_failed_host_preserves_raster_readiness_and_cooperative_cpu_refusal() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":12,"height":3})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + h.app.render_workspace.view.method = method; + h.app.render_workspace.path_host = PathHost::NotStarted; + let baseline = image_params(&h.app); + if method == ImageMethod::Raster { + assert!(baseline.is_ok(), "cooperative Raster must be available: {baseline:?}"); + } else { + assert_eq!(method, ImageMethod::CpuRaytrace); + let error = baseline.as_ref().unwrap_err(); + assert!(error.contains("CPU raytracing"), "cooperative CPU must retain its own host refusal: {error}"); + assert_ne!(error, h.app.tr("render.gpu_unavailable")); + } + let baseline_commands = ["render.preflight", "render.start"].map(|id| { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, method == ImageMethod::Raster, "{method:?}: {id}"); + assert_eq!(info.disabled_reason.as_deref(), baseline.as_ref().err().map(String::as_str), "{method:?}: {id}"); + (id, info.enabled, info.disabled_reason) + }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let reason = "Deliberate GPU-only refusal must not replace another method's readiness."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_eq!(image_params(&h.app), baseline, "{method:?}: preserve the exact success or rejection"); + for (id, enabled, disabled_reason) in baseline_commands { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, enabled, "{method:?}: {id}"); + assert_eq!(info.disabled_reason, disabled_reason, "{method:?}: {id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export() { + use solidcraft_engine::render::job::{RectangleLightOptions, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export") { + return; + } + h.app.render_workspace.view.raytrace.area_lights = Some(vec![RectangleLightOptions { + center_mm: [5.0, 4.0, 20.0], + edge_u_mm: [4.0, 0.0, 0.0], + edge_v_mm: [0.0, -4.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + h.app.render_workspace.view.raytrace.area_samples = Some(4); + h.app.render_workspace.view.raytrace.seed = Some(73); + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [0.25, 0.5, 1.0], + intensity: 3.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 0.75; + let expected = h.app.render_workspace.view.raytrace.area_lights.clone().unwrap(); + assert_eq!(expected.len(), 2); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Existing helper dispatches the real Snapshot, receives its real reply, + // validates real native PNG bytes/hash, drains the reply and paints the cache. + let id = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), id); + let status = job.status().unwrap(); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(options.area_lights.as_ref(), Some(&expected)); + assert_eq!(options.area_samples, Some(4)); + assert_eq!(options.seed, Some(73)); + assert_eq!(options.exposure_ev, 0.75); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + let (cached, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + let frame = job.frame().unwrap().unwrap(); + assert_eq!((cached.job, cached.png_sha256), (id, frame.info.png_sha256.clone())); + assert_eq!((cached.width, cached.height, samples, complete), (16, 16, 16, true)); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final() { + use solidcraft_engine::render::job::{CpuHost, JobId, Phase, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.raytrace.seed = Some(91); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let first = interactive_hold_real_completed_callback(&mut h); + let old = first.job.id(); + let old_options = first.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(old_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 2.0); + assert_eq!((old_options.area_samples, old_options.seed), (Some(4), Some(91))); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.area_lights.as_mut().unwrap().first_mut().unwrap().intensity = 1.5; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "light edit must detach the old owned job"); + first.sender.send(first.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &first.job); + + interactive_clear_acceptance_frame(&mut h, epoch + 0.601, true); + let second = interactive_hold_real_completed_callback(&mut h); + assert_ne!(second.job.id(), old); + let new_options = second.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(new_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 1.5); + assert_eq!((new_options.area_samples, new_options.seed), (Some(4), Some(91))); + let final_host = CpuHost::cooperative(); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(final_host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + let retained = final_host.admitted_bytes(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.7, false); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + second.sender.send(second.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.8, false, true); + assert!(!painted, "a final-suspended late LED reply cannot fill the preview cache"); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &second.job); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(final_host.admitted_bytes(), retained); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued, "Off cannot cancel the unrelated final"); + final_job.cancel().unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle() { + use solidcraft_engine::render::job::DirectionalLightOptions; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle") { + return; + } + h.app + .run( + "appearance.assign", + json!({"bodies":["Subject"],"color":"#808080","opacity":1.0, + "pbr":{"metallic":0.0,"roughness":1.0,"dielectric_ior":1.0}}), + ) + .unwrap(); + // Front view sees the y=0 face normally. All jittered rays through the + // central pixel stay inside that face, so neither coverage nor noise is an oracle. + h.app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, 4.0, 2.0); + h.app.cam.yaw = 0.0; + h.app.cam.pitch = 0.0; + h.app.cam.roll = 0.0; + h.app.cam.distance = 10.0; + h.app.cam.fov = 0.0; + h.app.cam.up = solidcraft_engine::render::UpAxis::Z; + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + h.app.render_workspace.view.raytrace = solidcraft_engine::render::job::RaytraceOptions { + lights: Some(vec![DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 0.5 }]), + shadows: false, + ..Default::default() + }; + let camera = h.app.cam; + let final_options = h.app.render_workspace.view.raytrace.clone(); + let final_size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let mut previous_job = None; + let mut baseline_png = None; + let mut previous_visual = None; + for (step, ev) in [0.0_f64, 1.0, -1.0, 0.0].into_iter().enumerate() { + let time = epoch + step as f64; + h.app.render_workspace.view.draft.exposure_ev = ev; + interactive_clear_acceptance_frame(&mut h, time, false); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + if let Some(previous) = previous_visual { + assert!(visual > previous, "each committed EV must invalidate the previous image"); + } + previous_visual = Some(visual); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + // This is the real runtime request, not a test-only renderer request. + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["exposure_ev"], 0.0, "outer EV must not duplicate the CPU EV"); + assert_eq!(wire["raytrace"]["exposure_ev"], ev); + interactive_clear_acceptance_frame(&mut h, time + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.camera, camera); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, ev, "actual admitted job must carry EV exactly once"); + if let Some(previous) = previous_job { + assert_ne!(held.job.id(), previous, "an EV edit must not reuse the old admitted job"); + } + previous_job = Some(held.job.id()); + let frame = held.job.frame().unwrap().unwrap(); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + // Original closed-form oracle: index-matched opaque dielectric has no + // Fresnel/specular term, so L = IEC-sRGB(128) * 0.5 / pi at normal incidence. + // Apply 2^EV once, Reinhard once, then IEC sRGB once and round to eight bits. + // No renderer BRDF/transfer helper or measured baseline supplies expectations. + let encoded = 128.0_f64 / 255.0; + let albedo = ((encoded + 0.055) / 1.055).powf(2.4); + let exposed = albedo * 0.5 / std::f64::consts::PI * 2.0_f64.powf(ev); + let mapped = exposed / (1.0 + exposed); + let srgb = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; + let expected = (255.0 * srgb).round() as u8; + assert!(expected > 0 && expected < 255, "fixture must stay away from black and clipping"); + assert_eq!(png.get_pixel(7, 7).0, [expected, expected, expected, 255], "EV={ev}: actual native CPU PNG must match analytic radiance"); + if step == 0 { + baseline_png = Some(frame.png().to_vec()); + } else if step == 3 { + assert_eq!(frame.png(), baseline_png.as_ref().unwrap().as_slice(), "EV reversal must return the deterministic original PNG"); + } + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256), (held.job.id(), frame.info.png_sha256.clone())); + assert_eq!((samples, complete), (16, true)); + let uploaded = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert_eq!(pixels.size, [16, 16]); + assert_eq!( + pixels.pixels[7 * 16 + 7], + Color32::from_rgb(expected, expected, expected), + "the accepted texture must contain the analytic pixel" + ); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert_eq!(h.app.render_workspace.view.raytrace, final_options); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), final_size); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery") { + return; + } + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let original = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let original_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let path = h.dir.join("interactive-accepted-to-pending-original.hdr"); + let bytes = original_hdr_bytes(192, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: path.to_string_lossy().into_owned() }; + // Even a real valid file is not admitted until inspected. An already + // displayed CPU frame must disappear, not masquerade as the new HDR intent. + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, true, true); + assert!(!painted); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.5); + assert_eq!(error, h.app.tr("render.hdr_inspect_required")); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > original_visual); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + // A correcting inspection must respect explicit user pause. Resume then + // captures the actual checked HDR through Snapshot/CPU, rather than falling + // back to the old frame or manufacturing a successful callback. + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let checked = interactive_request(&h.app).unwrap(); + { + use sha2::{Digest, Sha256}; + assert_eq!(checked["environment"]["expected_sha256"], format!("{:x}", Sha256::digest(&bytes))); + } + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + interactive_clear_acceptance_frame(&mut h, epoch + 1.5, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(interactive::test_cache(&h.app).is_none(), "the earlier accepted image cannot return after correcting HDR"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let recovered = interactive_recovery_require_success(&mut h, epoch + 1.701, epoch + 1.8); + assert_ne!(recovered, original); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), recovered); + let frame = job.frame().unwrap().unwrap(); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!((cached.job, samples, complete), (recovered, 16, true)); + assert_eq!(interactive_request(&h.app).unwrap(), checked); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 2.0, true, true); + assert!(painted, "Pause retains the newly recovered actual frame"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + let (paused, paused_samples, paused_complete, paused_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (paused.job, paused.png_sha256, paused_samples, paused_complete, paused_texture), + (recovered, frame.info.png_sha256.clone(), 16, true, texture) + ); + assert!(!output.textures_delta.set.contains_key(&texture), "Pause reuses the recovered texture"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(job.frame().unwrap().unwrap().png(), frame.png()); + interactive_assert_final_export_isolation(&mut h, &job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +fn partial_png_contract_encode(width: u32, height: u32, pixels: Vec) -> Vec { + // Original unit input for the real decoder/receiver, not a CPU render receipt. + let pixels = image::RgbaImage::from_raw(width, height, pixels).unwrap(); + let mut png = std::io::Cursor::new(Vec::new()); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + png.into_inner() +} + +fn partial_png_contract_request() -> solidcraft_engine::render::job::ImageRequest { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, RaytraceOptions}; + ImageRequest { + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera: Default::default(), + width: 2, + height: 2, + background: [32, 64, 96], + transparent_background: false, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { progressive: Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 291 }), ..Default::default() }), + } +} + +fn partial_png_contract_info(png: &[u8]) -> solidcraft_engine::render::job::PartialPreviewInfo { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::{ + ExecutorId, + job::{AlphaConvention, ColourEncoding, FrameInfo, JobId, PartialPreviewInfo, PartialPreviewProjection}, + }; + // Synthetic descriptor for pure contract tests. No Host/JobHandle, capture, + // native executor or final registry is installed or claimed by this helper. + PartialPreviewInfo { + frame: FrameInfo { + job: JobId { session: 100, serial: 1, generation: 1 }, + scene_generation: 7, + backend: solidcraft_engine::render::builtin_backend().id, + executor: ExecutorId::new("cpu-raytrace").unwrap(), + width: 2, + height: 2, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + png_sha256: format!("{:x}", Sha256::digest(png)), + }, + sequence: 1, + source_width: 2, + source_height: 2, + completed_passes: 0, + updated_prefix: 3, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + } +} + +#[test] +fn partial_png_contract_four_pixels_separate_hit_miss_black_and_unknown() { + let request = partial_png_contract_request(); + // Independently derived IEC/Reinhard bytes for linear(.25,.5,1) at EV0: + // encode(1/5), encode(1/3), encode(1/2) = (124,156,188). + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 8192).unwrap(); + assert_eq!(decoded.pixels, vec![Color32::from_rgb(124, 156, 188), Color32::from_rgb(32, 64, 96), Color32::BLACK, Color32::TRANSPARENT,]); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 3); + assert!(sampling.source_unknown(), "global Unknown drives the added geometry gate"); + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(0, 1, Color32::TRANSPARENT, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 1, Color32::BLACK, request.background).is_ok()); +} + +#[test] +fn partial_png_contract_second_prefix_keeps_nonuniform_counts_and_resolved_coverage() { + let request = partial_png_contract_request(); + // Original second-prefix source means are(.5,.25,1) and(0,1,0). + // The second has C/N=.5, so covered green2 is mapped BEFORE coverage: + // linear(.5*decode8(32), 1/3+.5*decode8(64), .5*decode8(96)), + // encoded once = (20,162,68). These PNG inputs must never be regraded by UI. + let png = partial_png_contract_encode(2, 2, vec![156, 124, 188, 255, 20, 162, 68, 255, 0, 0, 0, 255, 32, 64, 96, 255]); + let mut info = partial_png_contract_info(&png); + info.sequence = 2; + info.completed_passes = 1; + info.updated_prefix = 2; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[2, 1, 1, 0], sampling, 8192).unwrap(); + assert_eq!( + decoded.pixels, + vec![Color32::from_rgb(156, 124, 188), Color32::from_rgb(20, 162, 68), Color32::BLACK, Color32::from_rgb(32, 64, 96),] + ); + let counts: Vec<_> = (0..4).map(|index| interactive::partial_sample_count(1, 2, index, 4, 16).unwrap()).collect(); + assert_eq!(counts, vec![2, 2, 1, 1]); + assert_eq!(sampling.sample_range(), (1, 2), "this is not uniform2SPP"); + assert_eq!(sampling.sampled_source_pixels(), 4); + assert!(!sampling.source_unknown(), "only the additional Unknown block ends; all M3 gates still apply"); +} + +#[test] +fn partial_png_contract_frontier_bounds_keep_full_pass_sentinel_and_never_wrap() { + for index in 0..4 { + assert_eq!(interactive::partial_sample_count(0, 0, index, 4, 16).unwrap(), 0); + assert_eq!(interactive::partial_sample_count(1, 0, index, 4, 16).unwrap(), 1); + assert_eq!(interactive::partial_sample_count(16, 0, index, 4, 16).unwrap(), 16); + } + for (s, k, i, p, target) in [ + (0, 4, 0, 4, 16), + (0, 0, 4, 4, 16), + (0, 0, u64::MAX, 4, 16), + (0, 0, 0, 0, 16), + (0, 0, 0, 4, 0), + (17, 0, 0, 4, 16), + (16, 1, 0, 4, 16), + (u32::MAX, 1, 0, 4, u32::MAX), + ] { + assert!(interactive::partial_sample_count(s, k, i, p, target).is_err()); + } +} + +#[test] +fn partial_png_contract_rejects_high_invalid_identity_without_burning_accepted_sequence() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let accepted = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::validate_partial_metadata(&expected, &info, png.len(), 4, Some(accepted)).unwrap().is_none()); + let mut invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.job.generation += 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.width = 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; // advancing sequence with unchanged frontier is not new work + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + let mut next = info.clone(); + next.sequence = 2; // legitimate lower-than-rejected99 publication + next.completed_passes = 1; + next.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).unwrap().is_some()); + next.sequence = 0; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).is_err()); +} + +#[test] +fn partial_png_contract_decoder_refuses_unknown_blur_coverage_and_malformed_png() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 1).is_err(), "no implicit Triangle resize of Unknown"); + assert!(interactive::decode_partial_image(&request, &info, b"not a PNG", &[1, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 1], sampling, 8192).is_err(), "Unknown has no covered sample"); + assert!(interactive::decode_partial_image(&request, &info, &png, &[2, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1], sampling, 8192).is_err()); + let bad_alpha = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 128, 0, 0, 0, 255, 0, 0, 0, 0]); + let bad_info = partial_png_contract_info(&bad_alpha); + let bad_sampling = interactive::validate_partial_metadata(&expected, &bad_info, bad_alpha.len(), 4, None).unwrap().unwrap(); + assert!( + interactive::decode_partial_image(&request, &bad_info, &bad_alpha, &[1, 0, 1, 0], bad_sampling, 8192).is_err(), + "metadata admitted; sampled physical coverage must already be opaque" + ); +} + +#[test] +fn partial_png_contract_shared_plan_keeps_unrepresented_unknown_globally_blocked() { + use sha2::{Digest, Sha256}; + let mut request = partial_png_contract_request(); + request.width = 2048; + request.height = 1; + let png = partial_png_contract_encode(1024, 1, [0, 0, 0, 255].repeat(1024)); + let mut info = partial_png_contract_info(&png); + info.source_width = 2048; + info.source_height = 1; + info.frame.width = 1024; + info.frame.height = 1; + info.frame.png_bytes = png.len() as u64; + info.frame.png_sha256 = format!("{:x}", Sha256::digest(&png)); + info.updated_prefix = 2047; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2048, 1] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 1024, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1; 1024], sampling, 8192).unwrap(); + assert!(decoded.pixels.iter().all(|pixel| *pixel == Color32::BLACK)); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 2047); + assert!(sampling.source_unknown(), "all1024 representatives known does not observe source pixel2047"); + let plan = solidcraft_engine::render::job::PartialPreviewPlan::new(2048, 1).unwrap(); + assert_eq!(plan.source_index(0).unwrap(), 0); + assert_eq!(plan.source_index(1023).unwrap(), 2046); + assert!(plan.source_index(1024).is_err()); +} + +#[test] +fn partial_png_contract_egui_clock_throttles_attempts_without_wall_time_or_fake_frames() { + use solidcraft_engine::render::job::JobId; + use std::time::Duration; + let job = JobId { session: 100, serial: 1, generation: 1 }; + assert!(interactive::partial_request_due(None, job, Duration::ZERO)); + let first = Some((job, Duration::ZERO)); // caller records every attempt, including false + assert!(!interactive::partial_request_due(first, job, Duration::from_millis(249))); + assert!(interactive::partial_request_due(first, job, Duration::from_millis(250))); + let second = Some((job, Duration::from_millis(250))); + assert!(!interactive::partial_request_due(second, job, Duration::from_millis(499))); + assert!(interactive::partial_request_due(second, job, Duration::from_millis(500))); + let mut newer = job; + newer.serial += 1; + assert!(interactive::partial_request_due(second, newer, Duration::from_millis(251))); + let clock = interactive::monotonic(Duration::from_millis(500), 0.499); + assert_eq!(clock, Duration::from_millis(500)); + assert!(!interactive::partial_request_due(Some((job, clock)), job, Duration::from_millis(499))); +} + +#[test] +fn partial_frame_visibility_paused_unknown_yields_to_final_priority() { + use interactive::FrameVisibility; + // Policy inputs only: no Host/JobHandle, fake CPU output or native receipt. + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + assert!(paused.paintable(), "normal M3 paused/stale image remains visible"); + assert!(paused.blocks_unknown(true), "source Unknown still blocks geometry while paused"); + assert!(!paused.blocks_unknown(false), "known source does not gain an extra gate"); + let preempted = FrameVisibility { final_active: true, ..paused }; + assert!(!preempted.paintable()); + assert!(!preempted.blocks_unknown(true), "an image hidden by a manual final cannot reserve the Model canvas"); + // This is the nonwaiting case: both production paint and the Unknown arm + // decline it, so the existing parent can reach its visible Raster fallback. +} + +#[test] +fn partial_frame_visibility_error_or_missing_texture_cannot_claim_unknown_canvas() { + use interactive::FrameVisibility; + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + for hidden in [ + FrameVisibility { has_error: true, ..paused }, + FrameVisibility { texture_ok: false, ..paused }, + FrameVisibility { has_context: false, ..paused }, + FrameVisibility { paused: false, ..paused }, + ] { + assert!(!hidden.paintable()); + assert!(!hidden.blocks_unknown(true), "hidden pixels cannot suppress visible Raster or its geometry targets"); + } + let current = FrameVisibility { paused: false, stale: false, revision_matches: true, ..paused }; + assert!(current.paintable()); + assert!(current.blocks_unknown(true), "all-known representatives cannot erase global source Unknown"); + assert!(!FrameVisibility { stale: true, ..current }.blocks_unknown(true)); + assert!(!FrameVisibility { revision_matches: false, ..current }.blocks_unknown(true)); + // Existing waiting/input-cleanup regressions stay in the untouched222 prefix. + // The production awaiting_current_frame arm is not gated by this predicate. +} + +mod cpu_optical_material_routing { + use super::*; + + fn bind_recipe(h: &mut Harness, name: &str, recipe: &str, boundary: materials::Boundary) { + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == name).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(recipe).unwrap(); + // These represent explicit author actions, not a converter's guesses. + binding.glass.boundary = boundary; + binding.cpu_optics = true; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + } + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"center":[0,0,2],"body_name":"Optics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.shadows = false; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [1.0; 3]; + h.app.render_workspace.view.cpu.intensity = 1.0; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.background = [255; 3]; + h.app.cam = Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + h.app.session.mark_saved(); + h + } + + fn wire(h: &Harness) -> Value { + runtime_image_request(&h.app, false).unwrap() + } + + fn directional_shadow_fixture(choices: &[bool]) -> Harness { + use solidcraft_engine::render::job::DirectionalLightOptions; + assert!(!choices.is_empty() && choices.len() <= 2); + let mut h = Harness::new(); + for index in 0..choices.len() { + h.app + .run("solid.box", json!({"length":2,"width":2,"height":2,"center":[index as f64 * 4.0,0,2],"body_name":format!("Shadow{index}")})) + .unwrap(); + } + h.app.run("render.scene", json!({})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.shadows = true; + h.app.render_workspace.view.raytrace.lights = + Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }]); + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.materials.enabled = true; + let targets = materials::read_targets(&mut h.app).unwrap(); + for (index, shadows) in choices.iter().copied().enumerate() { + let target = targets.iter().find(|target| target.name == format!("Shadow{index}")).unwrap().clone(); + let mut binding = materials::Binding::new(target, &h.app); + binding.cpu_optics = true; + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.shadows = shadows; + h.app.render_workspace.view.materials.bindings.push(binding); + } + h.app.session.mark_saved(); + h + } + + fn directional_shadow_refusal_is_atomic(h: &Harness, key: Option<&str>) { + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"preserve"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let options = json!(h.app.render_workspace.view.raytrace); + let error = materials::params(&h.app, &mut request).unwrap_err(); + if let Some(key) = key { + assert!(error.contains(h.app.tr(key)), "{key}: {error}"); + } + assert_eq!(request, before); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert_eq!(json!(h.app.render_workspace.view.raytrace), options); + } + + #[test] + fn cpu_directional_shadow_uniform_assignments_lower_typed_wire_without_changing_authored_options() { + use solidcraft_engine::render::job::{CpuDielectricTransport, CpuProgressiveOptions, RaytraceOptions}; + for shadows in [false, true] { + for progressive in [false, true] { + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + let mut h = directional_shadow_fixture(&[shadows, shadows]); + h.app.render_workspace.view.raytrace.dielectric_transport = policy; + h.app.render_workspace.view.raytrace.progressive = + progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let mut expected = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut expected).unwrap(); + let request = runtime_image_request(&h.app, false).unwrap(); + let mut options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + options.validate().unwrap(); + assert_eq!(options.directional_shadow_transmission, shadows); + assert!(options.shadows); + assert_eq!(options.dielectrics.len(), 2); + assert_eq!(options.dielectric_transport, policy); + assert_eq!(options.progressive, h.app.render_workspace.view.raytrace.progressive); + assert!(options.dielectrics.iter().all(|body| body.ior == 1.5 && body.absorption_per_mm == [0.0; 3])); + assert!(request["raytrace"]["dielectrics"].as_array().unwrap().iter().all(|body| body.get("shadow_transmission").is_none())); + if !shadows { + assert!(request["raytrace"].get("directional_shadow_transmission").is_none()); + } + options.dielectrics.clear(); + options.directional_shadow_transmission = false; + assert_eq!(json!(options), expected["raytrace"], "no other CPU option may change"); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + } + } + } + } + + #[test] + fn cpu_directional_shadow_mixed_body_choices_refuse_both_orders_without_erasing_off() { + for choices in [[false, true], [true, false]] { + let h = directional_shadow_fixture(&choices); + directional_shadow_refusal_is_atomic(&h, Some("render.cpu_shadow_mixed")); + } + } + + #[test] + fn cpu_directional_shadow_all_on_keeps_global_shadows_environment_nesting_and_light_refusals() { + for case in ["global_off", "constant", "hdr", "nested", "reflections", "punctual", "area"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "global_off" => h.app.render_workspace.view.raytrace.shadows = false, + "constant" => h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant, + "hdr" => { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-shadow-adapter.hdr"); + } + "nested" => h.app.render_workspace.view.cpu.nested_media = true, + "reflections" => h.app.render_workspace.view.raytrace.reflections = Some(Default::default()), + "punctual" => { + h.app.render_workspace.view.raytrace.punctual_lights = Some( + serde_json::from_value(json!([{ + "position_mm":[0,0,100],"color":[1,1,1],"intensity":2,"reference_distance_mm":100,"minimum_distance_mm":0.01 + }])) + .unwrap(), + ); + } + "area" => { + h.app.render_workspace.view.raytrace.area_lights = Some( + serde_json::from_value(json!([{ + "center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3 + }])) + .unwrap(), + ); + } + _ => unreachable!(), + } + h.app.render_workspace.view.raytrace.validate().unwrap(); + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_all_on_preserves_identity_permission_duplicate_and_boundary_gates() { + for case in ["stale", "duplicate", "closed", "permission"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "stale" => { + h.app.run("appearance.assign", json!({"bodies":["Shadow0"],"color":"#123456"})).unwrap(); + } + "duplicate" => { + let duplicate = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(duplicate); + } + "closed" => h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Closed, + "permission" => h.app.render_workspace.view.materials.bindings[0].cpu_optics = false, + _ => unreachable!(), + } + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_inactive_off_body_is_not_selected_for_transmission() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.bindings[1].enabled = false; + let request = runtime_image_request(&h.app, false).unwrap(); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert!(options.directional_shadow_transmission); + assert_eq!(options.dielectrics.len(), 1); + assert_eq!(options.dielectrics[0].body_name, "Shadow0"); + assert!(!h.app.render_workspace.view.materials.bindings[1].glass.shadows); + assert!(!h.app.render_workspace.view.materials.bindings[1].enabled); + } + + #[test] + fn cpu_directional_shadow_default_false_and_conflicting_global_intent_are_preserved() { + use solidcraft_engine::render::job::RaytraceOptions; + assert!(!RaytraceOptions::default().directional_shadow_transmission); + assert!(json!(RaytraceOptions::default()).get("directional_shadow_transmission").is_none()); + let h = directional_shadow_fixture(&[false, false]); + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + request["raytrace"]["directional_shadow_transmission"] = json!(true); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_shadow_conflict"))); + assert_eq!(request, before); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.enabled = false; + let before = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + assert_eq!(request, before, "disabled materials do not rewrite an unrelated request"); + } + + #[test] + fn cpu_directional_shadow_adapter_messages_are_delivered_in_nine_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in ["render.cpu_directional_shadow_help", "render.cpu_shadow_conflict", "render.cpu_shadow_mixed"] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + #[test] + fn explicit_cpu_recipe_builds_typed_optics_with_independent_linear_units_and_no_design_edit() { + use solidcraft_engine::render::{ + job::{DielectricBoundary, RaytraceOptions}, + transmission::Transmission, + }; + let h = fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let request = wire(&h); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(options.dielectrics.len(), 1); + let material = &options.dielectrics[0]; + assert_eq!((material.body_index, material.body_name.as_str()), (0, "Optics")); + assert_eq!(material.boundary, DielectricBoundary::ClosedBox); + assert_eq!(material.ior, 1.5); + assert_eq!(material.thickness_mm, 0.0); + let [r, g, b] = material.absorption_per_mm; + assert!((r - 0.005050676829379866).abs() < 1e-15); + assert!((g - 0.0025125839633753626).abs() < 1e-15); + assert_eq!(b, 0.0); + // This tests coefficient lowering only. Native pixel tests below test transport. + let medium = Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + for (distance, expected) in [(4.0, [0.98, 0.99, 1.0]), (8.0, [0.9604, 0.9801, 1.0])] { + let t = medium.attenuation(distance).unwrap(); + for (actual, expected) in [t.x, t.y, t.z].into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12); + } + } + assert!(request["raytrace"].get("clear_coats").is_none()); + assert!(request["raytrace"].get("textures").is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(setups::snapshot(&h.app).is_err(), "transient CPU optics are not portable GPU saved optics"); + } + + #[test] + fn legacy_gpu_binding_and_closed_recipe_still_need_explicit_cpu_route_and_box_choice() { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = false; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_explicit"))); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_boundary"))); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let mut gpu = json!({}); + materials::params(&h.app, &mut gpu).unwrap(); + assert_eq!(gpu["raytrace"]["dielectrics"][0]["boundary"], "closed_mesh"); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + } + + #[test] + fn thin_recipe_preserves_authored_shadow_intent_until_explicit_edit() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].glass = materials::Glass::recipe("starter.glass.thin-clear").unwrap(); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_unsupported"))); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + // User deliberately disables the distinct GPU transmitted-shadow approximation. + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + let request = wire(&h); + assert_eq!(request["raytrace"]["dielectrics"][0]["boundary"], "thin_sheet"); + assert_eq!(request["raytrace"]["dielectrics"][0]["thickness_mm"], 2.0); + assert!(request["raytrace"]["dielectrics"][0].get("shadow_transmission").is_none()); + // The box fixture is NOT a certified thin surface; native admission must refuse below. + } + + #[test] + fn unsupported_optical_intent_refuses_atomically_instead_of_erasing_flags_or_maps() { + for case in ["coat", "maps", "shadows", "subsurface", "no_glass"] { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + match case { + "coat" => binding.coat_enabled = true, + "maps" => { + binding.maps_enabled = true; + binding.maps.normal = "authored-normal.png".into(); + } + "shadows" => binding.glass.shadows = true, + "subsurface" => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => { + binding.glass_enabled = false; + binding.coat_enabled = true; + } + } + let intent = format!("{:?}", h.app.render_workspace.view.materials); + let mut request = json!({"settings":{"exposure_ev":0},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).is_err(), "{case}"); + assert_eq!(request, before, "failed lowering must not partially replace CPU options: {case}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), intent, "{case}"); + } + } + + #[test] + fn cpu_optical_request_preserves_hdr_and_all_preexisting_cpu_numeric_options() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = fixture(); + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "budget":"studio","primary_samples":4,"shadows":true, + "lights":[{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}], + "punctual_lights":[{"position_mm":[0,0,100],"color":[0.25,0.5,1],"intensity":4, + "reference_distance_mm":100,"minimum_distance_mm":0.01,"cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}}], + "area_lights":[{"center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3}], + "area_samples":16,"seed":42 + })).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-optical-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.75; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + let base = json!(h.app.render_workspace.view.raytrace); + let mut request = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut request).unwrap(); + let cpu_request = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + let mut decoded: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(decoded.dielectrics.len(), 1); + decoded.dielectrics.clear(); + assert_eq!(json!(decoded), cpu_request["raytrace"], "only typed dielectrics may change"); + assert_eq!(request["environment"], cpu_request["environment"]); + assert_eq!(request["environment"]["path"], "not-read-by-optical-ui.hdr"); + assert_eq!(request["settings"]["exposure_ev"], 0.0); + assert_eq!(request["raytrace"]["exposure_ev"], 1.25); + assert_eq!(json!(h.app.render_workspace.view.raytrace), base); + } + + #[test] + fn optical_binding_refuses_hidden_changed_ordinal_wrong_feature_and_wrong_document() { + let mut h = fixture(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(runtime_image_request(&h.app, false).is_err(), "visibility need not change revision"); + h.app.session.visibility.hidden_bodies.clear(); + assert!(runtime_image_request(&h.app, false).is_ok()); + h.app.render_workspace.view.materials.bindings[0].target.ordinal = 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().feature += 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().occurrence_path = vec![999]; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + let document = h.app.session.doc.clone(); + h.app.session.doc = Arc::new((*document).clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "same numerical revision is not same document"); + } + + #[test] + fn optical_revalidation_is_explicit_and_same_body_only() { + let mut h = fixture(); + let mut original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + materials::revalidate(&mut h.app, &mut original).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + assert!(runtime_image_request(&h.app, false).is_ok()); + original.target.name = "Same name is insufficient".into(); + assert!(materials::revalidate(&mut h.app, &mut original).is_err()); + assert_eq!(original.target.name, "Same name is insufficient"); + } + + #[test] + fn optical_limits_duplicates_and_hostile_coefficients_keep_original_request_intact() { + let mut h = fixture(); + for bad in [f64::NAN, f64::INFINITY, -1.0, 3.01] { + h.app.render_workspace.view.materials.bindings[0].glass.ior = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.ior = 1.5; + for bad in [f64::NAN, f64::INFINITY, -0.1, 100.01] { + h.app.render_workspace.view.materials.bindings[0].glass.absorption[0] = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.absorption = [0.0; 3]; + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(original.clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "duplicate target is not two media"); + h.app.render_workspace.view.materials.bindings = vec![original; 9]; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn progressive_optics_preserves_identity_and_saved_gpu_conflicts_without_mutation() { + let mut h = fixture(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + let progressive_final = runtime_image_request(&h.app, false).unwrap(); + let final_options: RaytraceOptions = serde_json::from_value(progressive_final["raytrace"].clone()).unwrap(); + final_options.validate().unwrap(); + assert_eq!(final_options.primary_samples, 1); + assert_eq!(final_options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(final_options.progressive.unwrap().seed, 0); + let optics = progressive_final["raytrace"]["dielectrics"].clone(); + assert_eq!(optics.as_array().unwrap().len(), 1); + assert_eq!(optics[0]["body_name"], "Optics"); + assert_eq!(optics[0]["boundary"], "closed_box"); + assert_eq!(optics[0]["ior"], 1.5); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + let from_progressive = interactive_request(&h.app).unwrap(); + assert_eq!(from_progressive["raytrace"]["dielectrics"], optics, "preview conversion cannot erase or replace the authored optical material"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass_enabled); + h.app.render_workspace.view.raytrace.progressive = None; + let from_fixed = interactive_request(&h.app).unwrap(); + assert_eq!(from_fixed["raytrace"]["dielectrics"], optics, "Fixed editor preview still carries certified optics"); + let progressive_input: RaytraceOptions = serde_json::from_value(from_progressive["raytrace"].clone()).unwrap(); + progressive_input.validate().unwrap(); + assert_eq!(progressive_input.primary_samples, 1); + assert_eq!(progressive_input.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(progressive_input.progressive.unwrap().seed, 0); + let fixed_input: RaytraceOptions = serde_json::from_value(from_fixed["raytrace"].clone()).unwrap(); + fixed_input.validate().unwrap(); + assert_eq!(fixed_input.primary_samples, 1); + assert!(fixed_input.progressive.is_none(), "the UI Fixed DTO stays Fixed until the engine preview conversion"); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none(), "constructing preview intent cannot change the manual-final editor"); + #[cfg(not(target_arch = "wasm32"))] + if native_host(&mut h, "progressive_bridge_obsolete_guard_adaptation") { + use solidcraft_engine::render::job::{JobId, Phase, interactive::VisualRevision}; + use std::time::Duration; + // Same original20x20/one-pixel/50-distance inputs: this is actual + // capture/admission/completion, not a Beer pixel oracle (jitter may miss). + let mut final_params = progressive_final.clone(); + final_params["progressive_feedback"] = json!(true); + let checked = h.app.run("render.preflight", final_params.clone()).unwrap(); + let started = h.app.run("render.start", final_params).unwrap(); + let final_id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let final_job = h.app.session.render_job_handle(final_id).unwrap(); + let final_status = final_job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error); + assert_eq!(serde_json::to_value(&final_status.request).unwrap(), checked["request"]); + assert_eq!(json!(final_status.request.raytrace), progressive_final["raytrace"]); + assert!(!final_status.options.nested_media); + assert!(final_job.protected_preview_report().unwrap().is_some()); + let final_bytes = final_job.frame().unwrap().unwrap().png().to_vec(); + for (index, params) in [&from_progressive, &from_fixed].into_iter().enumerate() { + let context = h.app.session.interactive_render().unwrap(); + context + .enable(VisualRevision { scene_generation: h.app.session.revision, visual_revision: index as u64 + 1 }, Duration::ZERO) + .unwrap(); + let ticket = context.capture(Duration::from_millis(200)).unwrap().unwrap(); + let snapshot = context.snapshot(&h.app.session, ticket, params).unwrap(); + assert!(snapshot.run().unwrap(), "real optical snapshot must be admitted/adopted"); + let job = context.current().unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(serde_json::to_value(&options.dielectrics).unwrap(), optics); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(options.progressive.unwrap().seed, 0); + assert_eq!((status.request.width, status.request.height), (1, 1)); + assert!(!status.options.nested_media); + assert_eq!(job.id(), ticket.job_id()); + assert!(job.frame().unwrap().is_some()); + assert!(h.app.session.render_job_handle(job.id()).is_err(), "Interactive keeps a separate non-export owner"); + context.disable().unwrap(); + assert_eq!(h.app.session.render_job_handle(final_id).unwrap().frame().unwrap().unwrap().png(), final_bytes.as_slice()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), authored); + let mut request = wire(&h); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_optics_conflict"))); + assert_eq!(request, before); + let target = h.app.render_workspace.view.materials.bindings[0].target.stable_target.clone().unwrap(); + h.app + .render_workspace + .view + .draft + .optics + .set( + solidcraft_engine::doc::render_optics::SavedOptics { + target, + optics: solidcraft_engine::doc::render_optics::OpticalMaterial { + ior: 1.5, + absorption_per_mm: [0.0; 3], + boundary: solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedMesh, + thickness_mm: 0.0, + shadow_transmission: false, + subsurface: None, + }, + }, + false, + ) + .unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + assert_eq!(h.app.render_workspace.view.draft.optics.len(), 1); + } + + #[test] + fn nested_cpu_route_is_an_explicit_cpu_choice_independent_of_gpu_legacy_state() { + let mut h = fixture(); + h.app.render_workspace.view.studio.nested_media = true; + assert_eq!(wire(&h)["nested_media"], false); + h.app.render_workspace.view.cpu.nested_media = true; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.studio.nested_media = false; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.cpu.nested_media = false; + assert_eq!(wire(&h)["nested_media"], false); + } + + #[cfg(not(target_arch = "wasm32"))] + fn native_host(h: &mut Harness, case: &str) -> bool { + use solidcraft_engine::render::job::CpuHost; + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + if !available { + let request = wire(h); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", request.clone()).is_err()); + assert!(h.app.run("render.start", request).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return false; + } + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=true"); + true + } + + #[cfg(not(target_arch = "wasm32"))] + fn check_start_pixel(h: &mut Harness, expected: [u8; 4]) { + use solidcraft_engine::render::job::{JobId, Phase}; + let request = image_params(&h.app).unwrap(); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"], request["raytrace"]["dielectrics"]); + assert_eq!(image_params(&h.app).unwrap(), request, "Check and Start must capture identical optical intent"); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert_eq!(status.options.nested_media, request["nested_media"].as_bool().unwrap()); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(*image.get_pixel(0, 0), image::Rgba(expected)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_box_reaches_same_cpu_check_start_and_real_beer_pixels() { + let mut h = fixture(); + if !native_host(&mut h, "library_box") { + return; + } + // Explicit author edit isolates Beer: index-matched boundaries have zero + // Fresnel reflection, 4 mm actual distance yields [.98,.99,1]. + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.ior = 1.0; + glass.recipe = None; + check_start_pixel(&mut h, [187, 187, 188, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_admission_preserves_opacity_and_refuses_false_thin_certificate() { + let mut h = fixture(); + if !native_host(&mut h, "opacity_and_certificate") { + return; + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Thin; + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "twelve triangles are not a thin-sheet certificate"); + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].opacity, 0.25); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_thin_library_recipe_uses_actual_imported_planar_certificate_and_virtual_distance() { + let mut h = fixture(); + if !native_host(&mut h, "library_thin") { + return; + } + let path = h.dir.join("original-optical-sheet.stl"); + // Original one-triangle geometry, not a box proxy or commercial fixture. + std::fs::write(&path, b"solid OriginalSheet\nfacet normal 0 0 1\nouter loop\nvertex -20 -20 2\nvertex 20 -20 2\nvertex 0 20 2\nendloop\nendfacet\nendsolid OriginalSheet\n").unwrap(); + h.app.run("file.insert_mesh", json!({"path":path,"name":"OriginalSheet"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + let targets = materials::read_targets(&mut h.app).unwrap(); + assert_eq!(targets.len(), 1); + let name = targets[0].name.clone(); + bind_recipe(&mut h, &name, "starter.glass.thin-clear", materials::Boundary::Thin); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "do not silently delete the recipe's shadow intent"); + glass.shadows = false; // explicit compatible user policy + glass.ior = 1.0; // explicit index-matched Beer experiment + glass.recipe = None; + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].mesh.triangles.len(), 1); + // 2 mm virtual normal distance -> [.95,.98,.99]; Reinhard+sRGB bytes. + check_start_pixel(&mut h, [185, 187, 187, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_nested_opt_in_preserves_real_child_medium_and_default_refusal() { + let mut h = fixture(); + if !native_host(&mut h, "library_nested") { + return; + } + h.app.run("solid.box", json!({"length":10,"width":10,"height":2,"center":[0,0,2],"operation":"new","body_name":"Inner"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + bind_recipe(&mut h, "Inner", "starter.glass.amber-tint", materials::Boundary::Box); + for binding in &mut h.app.render_workspace.view.materials.bindings { + binding.glass.ior = 1.0; // explicit index-matched experiment, not renderer conversion + binding.glass.recipe = None; + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["nested_media"], false); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("nested, touching or overlapping"), "{error}"); + } + h.app.render_workspace.view.cpu.nested_media = true; + // Geometry gives 2 mm outer + 2 mm inner, replacing rather than adding + // parent extinction inside the child. Linear RGB: + // sqrt(.98)*.84^(2/3), sqrt(.99)*.38^(2/3), .08^(2/3). + // Independent Reinhard+sRGB quantisation -> [182,158,110]. + check_start_pixel(&mut h, [182, 158, 110, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_refuses_face_alpha_and_general_closed_geometry_without_repairs() { + let mut h = fixture(); + if !native_host(&mut h, "face_alpha_and_sphere") { + return; + } + h.app.run("appearance.assign", json!({"body":"Optics","faces":[[0,0,4]],"color":"#abcdef","opacity":0.5})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + assert_eq!(scene.meshes[0].opacity, 1.0); + assert!(scene.meshes[0].faces.iter().any(|face| face.opacity == 0.5)); + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.app.run("solid.sphere", json!({"radius":3,"center":[30,0,3],"body_name":"Sphere","operation":"new"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Sphere", "starter.glass.low-iron-clear", materials::Boundary::Box); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "an explicitly selected Box still needs an actual box certificate"); + } + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Box); + } + + #[test] + fn cpu_optics_preserves_reflection_intent_for_existing_transport_conflict() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + cpu::set_reflection(&mut h.app, "Optics", Some(ReflectionMode::Mirror)).unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Optics"); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + // Retaining both preserves the engine's explicit same-target transport + // refusal; the adapter does not silently delete the reflection binding. + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + } + + #[test] + fn cpu_optics_keeps_reflections_on_a_separate_exact_body() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[30,0,0],"body_name":"Reflector","operation":"new"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let before = h.app.render_workspace.view.raytrace.reflections.clone().unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"], json!(before)); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Reflector"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_original_library_ior_and_hdr_survive_check_start_and_captured_file_change() { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::job::{JobId, Phase}; + let mut h = fixture(); + if !native_host(&mut h, "library_ior_hdr") { + return; + } + let path = h.dir.join("original-optical-white.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input(path.to_str().unwrap()); + h.app.render_workspace.view.cpu.samples = 4; + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"][0]["ior"], 1.5, "the original recipe's IOR reaches the real consumer"); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["request"]["raytrace"], request["raytrace"]); + assert_eq!(image_params(&h.app).unwrap(), request); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + // Start has captured immutable bytes; this does not depend on whether + // its tiny job has already finished by the time the file is replaced. + std::fs::write(&path, b"changed after capture").unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + // CPU status carries exactly 32 byte values; the captured request uses + // the canonical lowercase hex HdrId wire form. Normalize independently + // of HdrId's production serializer/parser and keep absent/type failures. + let captured_sha256: [u8; 32] = serde_json::from_value(json!(status.environment).get("source_sha256").unwrap().clone()).unwrap(); + let expected_hex = request["environment"]["expected_sha256"].as_str().unwrap(); + assert_eq!(expected_hex.len(), 64); + assert!(expected_hex.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))); + let expected_sha256: [u8; 32] = std::array::from_fn(|index| u8::from_str_radix(&expected_hex[index * 2..index * 2 + 2], 16).unwrap()); + let original_sha256: [u8; 32] = Sha256::digest(&bytes).into(); + assert_eq!(captured_sha256, expected_sha256); + assert_eq!(captured_sha256, original_sha256); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + assert!(pixels.get_pixel(0, 0).0[..3].iter().all(|channel| *channel > 0), "real optical output must not be black"); + assert!(h.app.run("render.preflight", request).is_err(), "a fresh capture must detect the changed HDR"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_eight_optical_library_targets_admit_without_raising_the_ninth_target_limit() { + let mut h = fixture(); + if !native_host(&mut h, "eight_library_targets") { + return; + } + for index in 1..=8 { + h.app + .run( + "solid.box", + json!({"length":2,"width":2,"height":2,"corner":[30*index,0,0],"body_name":format!("Optics{index}"),"operation":"new"}), + ) + .unwrap(); + } + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + for index in 1..8 { + bind_recipe(&mut h, &format!("Optics{index}"), "starter.glass.low-iron-clear", materials::Boundary::Box); + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"].as_array().unwrap().len(), 8); + h.app.run("render.preflight", request).unwrap(); + bind_recipe(&mut h, "Optics8", "starter.glass.low-iron-clear", materials::Boundary::Box); + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn all_original_glass_recipes_keep_their_authored_coefficients_on_the_explicit_cpu_route() { + use solidcraft_engine::doc::appearance_pack::{Recipe, STARTER_PACK}; + let mut h = fixture(); + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let glass = materials::Glass::recipe(preset.id).unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.glass = glass; + if binding.glass.boundary == materials::Boundary::Closed { + binding.glass.boundary = materials::Boundary::Box; // explicit subset selection + } else { + assert!(binding.glass.shadows); + binding.glass.shadows = false; // explicit unsupported-policy edit + } + let request = wire(&h); + let material = &request["raytrace"]["dielectrics"][0]; + assert_eq!(material["ior"], recipe.dielectric_ior); + let sigma: [f64; 3] = serde_json::from_value(material["absorption_per_mm"].clone()).unwrap(); + for (sigma, transmission) in sigma.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + count += 1; + } + assert_eq!(count, 6); + assert!(materials::Glass::recipe("SELENE-AP-029").is_err(), "an opaque vial surrogate does not become physical glass"); + } + + #[test] + fn cpu_optical_route_messages_are_present_in_all_nine_delivered_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in [ + "render.cpu_optics_boundary", + "render.cpu_optics_conflict", + "render.cpu_optics_enable", + "render.cpu_optics_explicit", + "render.cpu_optics_fixed", + "render.cpu_optics_help", + "render.cpu_optics_limit", + "render.cpu_optics_request", + "render.cpu_optics_saved", + "render.cpu_optics_unsupported", + ] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + fn editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 2400.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("Optics")); + }, + ); + output.textures_delta.clear(); + } + + fn editor_click(h: &mut Harness, id: &str) { + let at = crate::scenario::rect_of(id).unwrap().center(); + for pressed in [true, false] { + editor_frame( + h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + editor_frame(h, vec![]); + } + + #[test] + fn clicked_cpu_optics_uses_existing_selection_editor_without_reinterpreting_gpu_binding() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = false; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + assert!(runtime_image_request(&h.app, false).is_err(), "opening the editor grants no CPU intent"); + editor_click(&mut h, "render:glass-recipe-select"); + editor_click(&mut h, "render:glass:starter.glass.low-iron-clear"); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert!(runtime_image_request(&h.app, false).is_err(), "Closed recipe cannot turn itself into a Box"); + editor_click(&mut h, "render:optics-boundary-box"); + assert_eq!(wire(&h)["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + editor_click(&mut h, "render:cpu-optics-nested"); + assert_eq!(wire(&h)["nested_media"], true); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(runtime_image_request(&h.app, false).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn clicked_cpu_boundary_does_not_silently_clear_transmitted_shadow_or_subsurface_intent() { + let mut h = fixture(); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.shadows = true; + glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + editor_click(&mut h, "render:optics-boundary-thin"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows); + assert!(glass.subsurface.is_some(), "selecting a different CPU boundary is not consent to remove scattering"); + assert!(runtime_image_request(&h.app, false).is_err()); + editor_click(&mut h, "render:optics-boundary-box"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "the GPU boundary default must not erase unsupported CPU shadow intent"); + assert!(glass.subsurface.is_some()); + assert!(runtime_image_request(&h.app, false).is_err()); + } +} + +// Additive scope imports for the sealed optical fixtures; UI247 stays byte-identical. +use serde_json::Value; +use solidcraft_engine::render::StandardView; + +#[cfg(not(target_arch = "wasm32"))] +mod manual_final_cpu_feedback_tests { + use super::*; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, HostKind, JobHandle, PartialPreviewPlan, PartialPreviewProjection, Phase}; + + fn fixture(width: u32, height: u32, samples: u32, background: [u8; 3], case: &str) -> Option { + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == HostKind::NativeWorker && host.is_available() && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = width; + view.draft.height = height; + view.draft.background = background; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.draft.exposure_ev = 0.0; + view.transparent = false; + view.raytrace = RaytraceOptions { + primary_samples: 1, + lights: Some(Vec::new()), + shadows: false, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 83 }), + ..Default::default() + }; + h.ctx.input_mut(|input| input.max_texture_side = 8192); + if !available { + let wire = json!({"integrator":"raytrace","progressive_feedback":true, + "settings":{"width":width,"height":height,"background":background}, + "raytrace":{"primary_samples":1,"lights":[],"shadows":false, + "progressive":{"samples_per_pixel":samples,"seed":83}}}); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", wire.clone()).is_err()); + assert!(h.app.run("render.start", wire).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.final_partial.is_none()); + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return None; + } + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=true"); + Some(h) + } + + fn actual_final(h: &mut Harness) -> JobHandle { + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + assert!(handle.frame().unwrap().is_some()); + assert!(handle.protected_preview_report().unwrap().is_some()); + handle + } + + // POLICY INPUTS ONLY, not a host-published PartialArc or a while-running receipt. + // Derive bounded display pixels from an actual completed native final, then + // author an explicit source-frontier descriptor to exercise the UI policy. + // No JobHandle, host status, PreviewInfo or GPU executor is fabricated. + fn install_policy_partial(h: &mut Harness, handle: &JobHandle, passes: u32, prefix: u64, sequence: u64) -> interactive::PartialSampling { + use sha2::{Digest, Sha256}; + let status = handle.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + let source = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + let plan = PartialPreviewPlan::new(status.request.width, status.request.height).unwrap(); + let mut pixels = Vec::new(); + for index in 0..usize::try_from(plan.pixels()).unwrap() { + let source_index = plan.source_index(index).unwrap(); + let count = passes + u32::from((source_index as u64) < prefix); + if count == 0 { + pixels.extend_from_slice(&[0, 0, 0, 0]); + } else { + let x = source_index % status.request.width as usize; + let y = source_index / status.request.width as usize; + pixels.extend_from_slice(&source.get_pixel(x as u32, y as u32).0); + } + } + let png = super::partial_png_contract_encode(plan.width(), plan.height(), pixels); + let mut frame_info = frame.info.clone(); + frame_info.width = plan.width(); + frame_info.height = plan.height(); + frame_info.png_bytes = png.len() as u64; + frame_info.png_sha256 = format!("{:x}", Sha256::digest(&png)); + let info = PartialPreviewInfo { + frame: frame_info, + sequence, + source_width: status.request.width, + source_height: status.request.height, + completed_passes: passes, + updated_prefix: prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }; + let covered = vec![0; usize::try_from(plan.pixels()).unwrap()]; // committed misses have zero hit coverage + let expected = interactive::PartialExpectation { + job: handle.id(), + scene_generation: status.scene_generation, + request: &status.request, + final_dimensions: [status.request.width, status.request.height], + }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), covered.len(), None).unwrap().unwrap(); + let image = + interactive::decode_partial_image(&status.request, &info, &png, &covered, sampling, h.ctx.input(|input| input.max_texture_side)).unwrap(); + let texture = h.ctx.load_texture("manual_final_policy_partial", image, egui::TextureOptions::NEAREST); + h.app.render_workspace.final_partial = Some(FinalPartialImage { info, sampling, image: Ok(texture) }); + sampling + } + + #[test] + fn native_manual_final_gui_opt_in_preserves_request_and_promotes_only_real_final() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "gui_opt_in") else { return }; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let stored = setups::snapshot(&h.app).unwrap(); + assert!(serde_json::to_value(&stored).unwrap().get("progressive_feedback").is_none()); + let offline = image_request(&h.app).unwrap(); + assert!(offline.get("progressive_feedback").is_none()); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + h.app.render_workspace.view.raytrace.progressive = None; + assert!(image_params(&h.app).unwrap().get("progressive_feedback").is_none()); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 9, seed: 83 }); + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, request); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!((status.request.width, status.request.height), (13, 7)); + let progressive = status.request.raytrace.as_ref().unwrap().progressive.unwrap(); + assert_eq!((progressive.samples_per_pixel, progressive.seed), (9, 83)); + let image = image::load_from_memory(handle.frame().unwrap().unwrap().png()).unwrap().to_rgba8(); + assert!(image.pixels().all(|pixel| pixel.0 == [17, 89, 203, 255])); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert!(display.preview.is_none() && display.partial.is_none()); + assert_eq!(display.logical_size, [13, 7]); + assert_eq!(display.info.job, handle.id()); + assert_eq!(setups::snapshot(&h.app).unwrap(), stored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn native_final_partial_policy_keeps_global_unknown_full_framing_and_real_final_priority() { + let Some(mut h) = fixture(1025, 1, 3, [17, 89, 203], "partial_policy") else { return }; + let handle = actual_final(&mut h); + assert!(h.app.render_workspace.view.completed.is_none()); + // The top-left 1024 representatives are known, but source pixel1024 is not. + let sampling = install_policy_partial(&mut h, &handle, 0, 1024, 1); + assert!(sampling.source_unknown()); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 1024); + let display = displayed_image(&h.app).unwrap(); + assert!(display.provisional() && display.partial.is_some() && display.preview.is_none()); + assert_eq!(display.logical_size, [1025, 1]); + assert_eq!((display.info.width, display.info.height), (1024, 1)); + assert_eq!(display.image.as_ref().unwrap().size(), [1024, 1]); + assert!(reduced_display(&h.app)); + let camera = Camera { distance: 37.0, ..Default::default() }; + h.app.render_workspace.view.result_camera = camera; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_job = Some(handle.id()); + let report = handle.protected_preview_report().unwrap(); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert_eq!(display.logical_size, [1025, 1]); + assert!(!reduced_display(&h.app)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + invalidate_images(&mut h.app); + assert!(h.app.render_workspace.final_partial.is_none()); + assert_eq!(handle.protected_preview_report().unwrap(), report, "presentation invalidation cannot reset the actual ledger"); + } + + #[test] + fn native_late_complete_policy_preserves_retained_export_then_reconciles_actual_frame() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "late_complete") else { return }; + let first = actual_final(&mut h); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + let first_bytes = first.frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.draft.background = [91, 33, 187]; + let second = actual_final(&mut h); + assert_eq!(h.app.render_workspace.view.completed, Some(first.id())); + install_policy_partial(&mut h, &second, 0, 5, 1); + assert!(displayed_image(&h.app).unwrap().provisional()); + let old_path = h.dir.join("manual-final-retained.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":old_path})).unwrap(); + assert_eq!(std::fs::read(&old_path).unwrap(), first_bytes); + // Regression oracle for the observed event order: + // frame read absent -> later real status Completed -> real frame promoted + // BEFORE provisional clear/fallback. This calls the production policy on + // an actual completed native handle; it does not fake the earlier read. + assert!(!final_job_still_running(&mut h.app, &second)); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + cache_render_images(&mut h.app, &ctx); + assert!(!displayed_image(&h.app).unwrap().provisional()); + assert!(h.app.render_workspace.final_partial.is_none()); + let new_path = h.dir.join("manual-final-current.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":new_path})).unwrap(); + assert_eq!(std::fs::read(&new_path).unwrap(), second.frame().unwrap().unwrap().png()); + let final_pixels = image::load_from_memory(&std::fs::read(&new_path).unwrap()).unwrap().to_rgba8(); + assert!(final_pixels.pixels().all(|pixel| pixel.0 == [91, 33, 187, 255])); + assert!(!final_job_still_running(&mut h.app, &first), "a different selected final cannot be reconciled through an old handle"); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + } + fn author_box_optics(h: &mut Harness) { + h.app.run("solid.box", json!({"length":200,"width":200,"height":4,"center":[0,0,2],"body_name":"ManualOptics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = 1; + view.draft.height = 1; + view.draft.background = [255; 3]; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.transparent = false; + view.draft.exposure_ev = 0.0; + view.raytrace.primary_samples = 1; + view.raytrace.lights = Some(Vec::new()); + view.raytrace.shadows = false; + view.cpu.environment = cpu::Environment::Constant; + view.cpu.color = [1.0; 3]; + view.cpu.intensity = 1.0; + h.app.cam = Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "ManualOptics").unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.cpu_optics = true; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + binding.glass.boundary = materials::Boundary::Box; // explicit author choice, not inferred geometry + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.session.mark_saved(); + } + + fn editor_text(h: &mut Harness, events: Vec) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(shape) => { + text.push_str(shape.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, text); + } + } + _ => {} + } + } + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 3200.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("ManualOptics")); + }, + ); + let mut text = String::new(); + for clipped in &output.shapes { + collect(&clipped.shape, &mut text); + } + output.textures_delta.clear(); + text + } + + #[test] + fn certification_note_draws_cpu_check_guidance_in_both_sampling_modes_and_legacy_gpu_note() { + let pending: Value = + serde_json::from_str(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pending/cpu-optical-certification.json"))) + .unwrap(); + let key = "render.cpu_optics_certification"; + for locale in ["ar", "de", "en", "es", "he", "ja", "ko", "vi", "zh"] { + assert_eq!(pending[locale].as_object().unwrap().len(), 1); + assert!(!pending[locale][key].as_str().unwrap().trim().is_empty()); + } + let mut h = Harness::new(); + h.ctx.global_style_mut(|style| style.animation_time = 0.0); + author_box_optics(&mut h); + h.app.render_workspace.view.raytrace.progressive = None; + let cpu_note = h.app.tr(key).to_string(); + let gpu_note = h.app.tr("render.material_certification").to_string(); + assert_ne!(cpu_note, key, "a missing catalog fallback is not a translated note"); + assert_ne!(gpu_note, "render.material_certification"); + let document = h.app.session.doc.clone(); + let before = ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed, + ); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let initial = editor_text(&mut h, Vec::new()); + if !initial.contains(&cpu_note) { + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + let at = crate::scenario::rect_of(&heading).unwrap().center(); + for pressed in [true, false] { + editor_text( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + } + for progressive in [None, Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 })] { + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = progressive; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&cpu_note), "{text}"); + assert!(!text.contains(&gpu_note), "{text}"); + } + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&gpu_note), "{text}"); + assert!(!text.contains(&cpu_note), "{text}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + before, + ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed + ) + ); + // Text/layout evidence only: selecting a note never certifies a CPU/GPU render. + } + + #[test] + fn native_progressive_optical_recipe_keeps_authored_ior_certificate_and_final_capture() { + let Some(mut h) = fixture(1, 1, 5, [255; 3], "progressive_optics") else { return }; + author_box_optics(&mut h); + // This optical capture fixture requires normal incidence. StandardView::Top + // intentionally stops short of the pole; author an exact canonical view + // locally, preserving the shared helper's real near-pole GUI path. + h.app.cam = Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, up: solidcraft_engine::render::UpAxis::Z, ..h.app.cam }; + assert!(h.app.cam.is_valid()); + assert_eq!(h.app.cam.fov, 0.0); + assert_eq!(h.app.cam.distance, 10.0); + assert_eq!(h.app.cam.target, solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0)); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (0.0, std::f64::consts::FRAC_PI_2, 0.0, solidcraft_engine::render::UpAxis::Z) + ); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 }); + // The orthographic pixel's entire jitter support lies in +/-4mm, + // strictly inside the independently authored +/-100mm box footprint. + assert_eq!(h.app.cam.half_height(), 4.0); + for (x, y) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { + let (origin, direction) = h.app.cam.ray(x, y, 1.0, 1.0); + assert!(direction.x.abs() < 1e-12 && direction.y.abs() < 1e-12); + assert!((direction.z.abs() - 1.0).abs() < 1e-12); + let point = origin + direction * ((4.0 - origin.z) / direction.z); + assert!(point.x.abs() <= 4.0 + 1e-9 && point.y.abs() <= 4.0 + 1e-9); + assert!(point.x.abs() < 100.0 && point.y.abs() < 100.0); + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + let optics = &request["raytrace"]["dielectrics"][0]; + assert_eq!(optics["body_name"], "ManualOptics"); + assert_eq!(optics["boundary"], "closed_box"); + assert_eq!(optics["ior"], 1.5, "the production recipe IOR is not reduced for this case"); + for (index, transmission) in [0.98_f64, 0.99, 1.0].into_iter().enumerate() { + let expected = -transmission.ln() / 4.0; + assert!((optics["absorption_per_mm"][index].as_f64().unwrap() - expected).abs() < 1e-15); + } + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert!(!status.options.nested_media); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + let pixel = pixels.get_pixel(0, 0).0; + assert_eq!(pixel[3], 255); + assert!(pixel[..3].iter().any(|value| *value > 0)); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + // Actual CPU capture/completion + nonblack optical smoke, not a full + // Fresnel/TIR oracle or a partial-optical-tree while-running receipt. + } +} + +// These exercise GUI navigation against the real cooperative Raster host. +// They do not qualify CPU raytracing, progressive cadence or GPU rendering. +fn auto_result_raster_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":3,"width":4,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.render_workspace.view.draft.width = 13; + h.app.render_workspace.view.draft.height = 7; + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h +} + +#[test] +fn auto_result_success_opens_once_and_explicit_model_survives_real_completion() { + use solidcraft_engine::render::job::Phase; + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + assert!(!h.app.render_workspace.view.result); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(h.app.render_workspace.view.result); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(ribbon::action_ready(&h.app, "render.export").is_err()); + let request = handle.status().unwrap().request; + assert_eq!((request.width, request.height, request.integrator), (13, 7, Integrator::Raster)); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.result); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result, "publication/repaint must respect an explicit Model selection"); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded cooperative Raster work must complete"); + assert_eq!((frame.info.width, frame.info.height), (13, 7)); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(ribbon::action_ready(&h.app, "render.export").is_ok()); + for _ in 0..3 { + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn auto_result_disabled_keeps_both_selected_views_through_start_and_completion() { + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + crate::prefs::set(&mut h.app, &json!({"render_open_result_on_start":false})).unwrap(); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(handle.frame().unwrap().is_none()); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + if handle.frame().unwrap().is_some() { + break; + } + } + assert!(handle.frame().unwrap().is_some(), "bounded cooperative Raster work must complete"); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + } +} + +#[test] +fn auto_result_check_invalid_start_and_real_queue_full_preserve_selected_view() { + use solidcraft_engine::render::job::Phase; + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.render_workspace.view.draft.width = 0; + assert!(ribbon::perform_job(&mut h.app, "render.preflight").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(ribbon::perform_job(&mut h.app, "render.start").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + h.app.render_workspace.view.draft.width = 13; + let request = image_params(&h.app).unwrap(); + let mut jobs = Vec::new(); + // Queue two real jobs without registering a GUI job. + // No pump or worker thread runs between admission and the third Start. + for _ in 0..2 { + let reply = h.app.session.execute("render.start", &request).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + jobs.push(handle); + } + ribbon::action_ready(&h.app, "render.start").unwrap(); + let error = ribbon::perform_job(&mut h.app, "render.start").unwrap_err(); + assert!(error.contains("this document already has an active and pending render"), "expected real document QueueFull: {error}"); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + for handle in jobs { + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn product_preview_exposure_is_bounded_without_rewriting_method_or_advanced_intent() { + let mut h = Harness::new(); + h.app.render_workspace.view.samples = 512; + h.app.render_workspace.view.max_depth = 8; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.shadows = false; + let cpu = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + let gpu = (h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len()); + let camera = h.app.cam; + for ev in [-32.0, -3.5, -0.0, 0.0, 1.75, 32.0] { + h.app.render_workspace.view.draft.exposure_ev = ev; + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, ev, "method selection cannot silently reset saved exposure intent"); + let preview = product_preview_exposure(&h.app).unwrap(); + // Model uses the common EV for every final method, even with Interactive Off. + // This intentionally supersedes this unpublished test's Raster-only helper contract. + assert_eq!(preview.ev(), ev as f32); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), cpu); + assert_eq!((h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed), gpu); + } + } + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -32.001, 32.001] { + h.app.render_workspace.view.draft.exposure_ev = invalid; + let error = product_preview_exposure(&h.app).unwrap_err(); + assert_eq!(error, h.app.tr("render.product_exposure_invalid")); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev.to_bits(), invalid.to_bits(), "a refusal must not clamp or replace intent"); + // The real Model show route must report the typed exposure refusal before + // its no-GPU fallback, without starting a final or Interactive capture. + let mut output = h.ctx.run_ui(Default::default(), |ui| show(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.text() == error)); + output.textures_delta.clear(); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), history); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn raster_shot_exposure_uses_the_existing_slider_and_one_undoable_saved_command() { + let mut h = frame_editor_fixture(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Exposure subject"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + select_image_method(&mut h.app, ImageMethod::Raster); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 0.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), saved.exposure_ev as f32); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + #[cfg(not(target_arch = "wasm32"))] + { + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let (_, geometry) = gpu_scene(&scene).unwrap(); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let capture = |exposure| { + crate::gpu::render_product_offscreen_exposure( + geometry.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], if camera.fov > 0.0 { 1.0 } else { 0.0 }], + 64, + false, + exposure, + ) + }; + if let Some(zero) = capture(Default::default()) { + let exposed = capture(product_preview_exposure(&h.app).unwrap()).expect("the same supported capture route must complete"); + assert_ne!(exposed, zero, "saved GUI exposure must reach actual product-shader pixels"); + assert_eq!(&exposed[..4], &zero[..4], "the capture backplate is not exposed"); + assert_eq!(capture(Default::default()).unwrap(), zero, "returning to zero restores the exact captured response"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=true"); + } else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GUI product capture is unavailable"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=false"); + } + } + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Original F1 regressions: real native accepted pixels, no injected cache/frame. +// This first alignment block covers accepted camera and framing, not a new +// proof of all possible scene/placement/visibility changes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let handle = interactive::test_current(&h.app).unwrap().unwrap(); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((accepted.job, samples, complete), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let end = at + egui::vec2(28.0, 12.0); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE }, + ], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(end)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Middle, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_ne!(h.app.cam.target, camera.target, "the real shared middle-pan must have moved the camera"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app), "this is known paused evidence, not the existing blank/Unknown guard"); + assert!(interactive::blocks_geometry_input(&h.app)); + let viewport = h.app.viewport.rect.unwrap(); + let geometry_rect = interactive::geometry_input_rect(&h.app, viewport); + let projection = crate::viewport::projection(&h.app, geometry_rect); + let current_hit = projection.to_screen(camera.target).unwrap(); + assert!(geometry_rect.contains(current_hit)); + assert!( + crate::viewport::pick(&h.app, &projection, current_hit) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }), + "prove there really is a current-camera target for the new guard to reject" + ); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none() && h.app.session.selection.is_empty()); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + let (retained, retained_samples, retained_complete, retained_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (retained.job, retained.png_sha256, retained_samples, retained_complete, retained_texture), + (job, accepted.png_sha256, samples, complete, texture) + ); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.01, false, true); + assert!(painted, "the retained image stays visible as a reference"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + interactive_assert_final_export_isolation(&mut h, &handle); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let viewport = h.app.viewport.rect.unwrap(); + let pixels = interactive::geometry_input_rect(&h.app, viewport); + assert!(pixels.width() < viewport.width(), "the original square image is letterboxed in this landscape viewport"); + assert!((pixels.width() - pixels.height()).abs() <= f32::EPSILON * pixels.height().max(1.0)); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assert!(!interactive::blocks_geometry_input(&h.app), "Pause alone and an earlier appearance edit cannot block aligned input"); + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Subject"].name, name); + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::blocks_geometry_input(&h.app)); + } + assign::stop(&mut h.app); + let selection = h.app.session.selection.clone(); + let outside_pixels = egui::pos2(viewport.left() + 1.0, viewport.center().y); + assert!(!pixels.contains(outside_pixels)); + interactive_canvas_input_click(&mut h, &mut time, outside_pixels, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection, "letterbox margins are not pixel-aligned CAD targets"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let width = h.app.render_workspace.view.draft.width; + assert!(!interactive::blocks_geometry_input(&h.app)); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "start a real drag against aligned accepted pixels"); + h.app.render_workspace.view.draft.width = width * 2; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(!assign::cancel(&mut h.app), "the blocked release must drain the real drag"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + (h.app.session.revision, h.app.session.undo.len()), + (revision, undo), + "the guard must stop a framing-only drag without relying on the document revision guard" + ); + h.app.render_workspace.view.draft.width = width; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the accepted aspect restores aligned same-camera input"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app), "the manual Result path owns its own camera and input policy"); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app) && interactive::blocks_geometry_input(&h.app)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +// Geometry/placement/visibility successor: original native snapshots and CAD +// commands only. No injected publications, host factory or scheduling barrier. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels") + else { + return; + }; + let world = h.app.session.interactive_cached_world_state().unwrap(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let retained = interactive::test_cache(&h.app).unwrap(); + assert_eq!((retained.0.job, retained.1, retained.2), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("solid.move", json!({"bodies":["Subject"],"translate":[2,0,0]})).unwrap(); + let moved = h.app.session.interactive_cached_world_state().unwrap(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "must reject before observed is refreshed, using accepted capture authority"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let center = moved.body("Subject").unwrap().mesh().bounds().center(); + let at = projection.to_screen(center).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }) + ); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let after = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (after.0.job, after.0.png_sha256, after.1, after.2, after.3), + (retained.0.job, retained.0.png_sha256, retained.1, retained.2, retained.3) + ); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned") + else { + return; + }; + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"center":[22,0,2],"body_name":"Other"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + let world = h.app.session.interactive_cached_world_state().unwrap(); + let camera = h.app.cam; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":false})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "unchanged world alone cannot certify a changed visible body set"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(world.body("Other").unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Other") }), + "a still-visible current-world target exists" + ); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":true})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the exact accepted visibility can restore alignment without recapture"); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Other".into() })); + assert!(!interactive::blocks_geometry_input(&h.app), "selection is not a scene invalidation"); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.doc.appearances.bodies["Other"].name, name); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert!(!interactive::blocks_geometry_input(&h.app), "render-only refresh must keep the accepted geometric identity usable"); + } + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world() { + for capture in [true, false] { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world") + else { + return; + }; + let component = h.app.run("component.create", json!({"name":"AlignmentPart","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"body_name":"Placed"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let world = h.app.session.world_state(); // Explicit real test preparation, never performed by the guard. + let placed = world.bodies.iter().find(|body| body.name != "Subject").unwrap().name.clone(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[3,0,0],"capture":capture})).unwrap(); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "a missing/stale prepared world is not accepted-scene authority"); + let moved = h.app.session.world_state(); // Warm through the ordinary API only in the original test. + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(interactive::blocks_geometry_input(&h.app), "warming a new current world must not bless the old accepted pixels"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(moved.body(&placed).unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == &placed) }) + ); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let new_job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + assert_ne!(new_job, job); + assert!(!interactive::blocks_geometry_input(&h.app), "only the new accepted capture can establish the moved scene"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +// Common Model EV must stop at captured-image boundaries; these use real producers. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "real show has no product-GPU fallback in this fixture"); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, false); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.raster_exposure_ev, 0.0, "CPU request must not gain a second Raster EV"); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, 1.0); + let frame = held.job.frame().unwrap().unwrap(); + let original = frame.png().to_vec(); + held.sender.send(held.reply).unwrap(); + let (mut accepted, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let texture = interactive::test_cache(&h.app).unwrap().3; + let uploaded = &accepted.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [16, 16]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + accepted.textures_delta.clear(); + + // Current capture first, then a paused image after a different common EV edit. + // Both must paint their captured texture, without entering the live Model branch. + for (step, ev) in [1.0, 2.0].into_iter().enumerate() { + if step == 1 { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.exposure_ev = ev; + } + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), ev as f32); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4 + step as f64 * 0.1), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.error_gpu_preview"))); + assert!(!output.textures_delta.set.contains_key(&texture), "captured PNG is not uploaded or graded again"); + output.textures_delta.clear(); + assert!( + h.ctx.tessellate(output.shapes, output.pixels_per_point).iter().any( + |shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty()) + ) + ); + let (cached, samples, complete, id) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256, samples, complete, id), (held.job.id(), frame.info.png_sha256.clone(), 16, true, texture)); + assert_eq!(held.job.frame().unwrap().unwrap().png(), original.as_slice()); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch a replacement capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn product_preview_exposure_does_not_regrade_or_validate_a_retained_real_result() { + let mut h = auto_result_raster_fixture(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded real cooperative Raster result"); + let original = frame.png().to_vec(); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + let mut texture = None; + for ev in [1.0, -1.0, f64::NAN] { + h.app.render_workspace.view.draft.exposure_ev = ev; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(&mut h.app, ui), + ); + assert!(h.app.render_workspace.view.result); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + if let Some(prior) = texture { + assert_eq!(id, prior); + assert!(!output.textures_delta.set.contains_key(&id)); + } else { + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [13, 7]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels + .pixels + .iter() + .zip(png.pixels()) + .all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + } + texture = Some(id); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.product_exposure_invalid"))); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty())) + ); + assert_eq!(handle.frame().unwrap().unwrap().png(), original.as_slice()); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + } + let path = h.dir.join("common-model-ev-retained-result.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), original); +} + +#[test] +fn editing_an_inactive_selected_shot_keeps_the_active_setup_draft_and_camera() { + let mut h = frame_editor_fixture(); + assert_eq!(shot::selected(&h.app), Some("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Studio", "selection does not activate a saved setup"); + let active = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let camera = h.app.cam; + let before = h.app.session.doc.to_json(); + let studio = h.app.session.doc.render.setups.get("Studio").cloned(); + let mut expected_hero = h.app.session.doc.render.setups["Hero"].clone(); + expected_hero.exposure_ev = 1.5; + let undo = h.app.session.undo.len(); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Hero"], expected_hero); + assert_eq!(h.app.session.doc.render.setups.get("Studio").cloned(), studio); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1, "only the saved Hero edit enters history"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); +} + +// Integration of the common ±32 EV contract with the existing Shot editor. +// This exercises egui input and the saved command, without opening a GPU device. +#[test] +fn cpu_shot_exposure_reaches_extended_range_via_slider_and_one_saved_command() { + let mut h = frame_editor_fixture(); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"job":{"method":"cpu_raytrace"},"exposure_ev":0.0}})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.875, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 16.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + // The shared production constructor captures portable intent without host admission. + assert!(!setups::has_runtime_inputs(&h.app)); + assert_eq!(image_request(&h.app).unwrap()["settings"]["exposure_ev"], json!(saved.exposure_ev)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Explicit catalogue staging, not a scalar appearance assignment or transport oracle. +mod glass_library_bridge { + use super::*; + use solidcraft_engine::{ + Sel, + doc::appearance_pack::{Recipe, STARTER_PACK}, + }; + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"body_name":"Optics"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Optics".into() }]})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.stage = Stage::Look; + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 64; + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.session.mark_saved(); + h + } + + #[test] + fn library_bridge_stages_all_six_authored_recipes_without_cpu_permission_or_design_changes() { + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut h = fixture(); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let options = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + library::stage_glass(&mut h.app, preset.id).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert_eq!(binding.target.name, "Optics"); + assert!(binding.target.stable_target.is_some()); + assert!(binding.glass_enabled && !binding.cpu_optics && !binding.maps_enabled && !binding.coat_enabled); + assert_eq!(binding.glass.recipe, Some(preset.id)); + assert_eq!(binding.glass.ior, recipe.dielectric_ior); + for (sigma, transmission) in binding.glass.absorption.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + match recipe.boundary { + solidcraft_engine::doc::appearance_pack::GlassBoundary::Closed => { + assert_eq!(binding.glass.boundary, materials::Boundary::Closed); + assert!(!binding.glass.shadows); + } + solidcraft_engine::doc::appearance_pack::GlassBoundary::Thin { thickness_mm } => { + assert_eq!(binding.glass.boundary, materials::Boundary::Thin); + assert_eq!(binding.glass.thickness, thickness_mm); + assert!(binding.glass.shadows, "preparing a Thin recipe is not consent to remove transmitted shadows"); + } + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), options); + assert!(runtime_image_request(&h.app, false).is_err(), "CPU permission is still explicit"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if items == &h.app.session.selection)); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + count += 1; + } + assert_eq!(count, 6); + } + + #[test] + fn library_bridge_requires_stable_glass_id_and_keeps_scalar_assignment_guards() { + let mut h = fixture(); + let opaque = STARTER_PACK.iter().find(|p| matches!(p.recipe, Recipe::Opaque(_))).unwrap(); + for id in ["Glass - Clear", "Glass Recipe - Low Iron Clear", opaque.id, "starter.glass.not-a-recipe"] { + assert!(library::stage_glass(&mut h.app, id).is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + let catalog = h.app.run("appearance.library", json!({})).unwrap(); + let glass = catalog["appearances"].as_array().unwrap().iter().find(|p| p["id"] == "starter.glass.low-iron-clear").unwrap(); + assert_eq!(glass["available"], false); + for appearance in ["starter.glass.low-iron-clear", "Glass Recipe - Low Iron Clear"] { + assert!(h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":appearance,"color":"#ffffff","opacity":1.0})).is_err()); + } + h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":"Glass - Clear"})).unwrap(); + assert!(h.app.session.doc.appearances.bodies["Optics"].opacity < 1.0); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "legacy alpha is never promoted to physical glass"); + } + + #[test] + fn library_bridge_refuses_face_component_empty_multiple_and_raster_targets() { + let mut h = fixture(); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + let hit = crate::viewport::Hit::Face { body: "Optics".into(), index: 0, point: solidcraft_engine::geom::Vec3::ZERO }; + let face = crate::viewport::candidate(&h.app, &[hit]).unwrap().1; + assert!(matches!(face, Sel::Face { .. })); + let component = h.app.run("component.create", json!({"name":"Unassigned component"})).unwrap(); + let occurrence = component["occurrence"].as_u64().unwrap(); + for selection in [ + vec![], + vec![face], + vec![Sel::Occurrence { path: vec![occurrence] }], + vec![Sel::Body { name: "Optics".into() }, Sel::Body { name: "Optics".into() }], + ] { + h.app.session.selection = selection; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + h.app.session.selection = vec![Sel::Body { name: "Optics".into() }]; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + } + + #[test] + fn library_bridge_hidden_stale_document_and_changed_target_never_refresh_a_binding() { + let mut h = fixture(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + h.app.session.visibility.hidden_bodies.clear(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings[0].target.ordinal += 1; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].target.ordinal, original.target.ordinal + 1); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.session.doc = Arc::new((*h.app.session.doc).clone()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err(), "CAD revision is not silently revalidated"); + } + + #[test] + fn library_bridge_conflicts_preserve_permission_shadows_scattering_and_other_material_intent() { + for conflict in 0..4 { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.thin-clear").unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = true; + match conflict { + 0 => binding.coat_enabled = true, + 1 => binding.maps_enabled = true, + 2 => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => binding.glass.ior = 1.7, + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_exact_repeat_preserves_existing_cpu_permission_disabled_state_and_values() { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + h.app.render_workspace.view.materials.bindings[0].enabled = false; + h.app.render_workspace.view.materials.enabled = false; + let before = format!("{:?}", h.app.render_workspace.view.materials); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + } + + #[test] + fn library_bridge_respects_authoring_and_cpu_target_caps_without_activating_other_bindings() { + for (method, count, active) in [(ImageMethod::GpuRaytrace, 128, false), (ImageMethod::CpuRaytrace, 8, true)] { + let mut h = fixture(); + h.app.render_workspace.view.method = method; + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|t| t.name == "Optics").unwrap(); + for i in 0..count { + let mut other = target.clone(); + other.name = format!("Other{i}"); + let mut binding = materials::Binding::new(other, &h.app); + binding.glass_enabled = active; + h.app.render_workspace.view.materials.bindings.push(binding); + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_keeps_closed_thin_and_strict_cpu_choices_explicit_without_a_transport_claim() { + let mut h = fixture(); + h.app.render_workspace.view.raytrace.dielectric_transport = solidcraft_engine::render::job::CpuDielectricTransport::StrictTir; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.25, 0.5, 0.75]; + h.app.render_workspace.view.cpu.intensity = 2.0; + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).is_err(), "Closed is not silently certified Box"); + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + let wire = runtime_image_request(&h.app, false).unwrap(); + assert_eq!(wire["raytrace"]["dielectric_transport"], "strict_tir"); + assert_eq!(wire["raytrace"]["dielectrics"][0]["ior"], 1.5); + assert_eq!(wire["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.25); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["environment"]["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(wire["raytrace"]["environment"]["intensity"], 2.0); + assert!(setups::snapshot(&h.app).is_err(), "transient staging never becomes saved CPU optics"); + // This checks routing only. A real StrictTir LimitExceeded remains FAIL for G02-C. + } + + #[test] + fn clicked_library_glass_action_reaches_existing_body_editor_and_never_reports_applied() { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + library::choose(&mut h.app, &mut view, "appearances", "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.library = view; + h.frames(3); + let doc = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:library:prepare-glass"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + assert!(!h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert!( + matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if matches!(items.as_slice(), [Sel::Body {name}] if name == "Optics")) + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + } + + #[test] + fn library_bridge_messages_cover_every_current_delivered_locale() { + let messages: Value = serde_json::from_str(include_str!("../../../assets/locales/pending/render-glass-library-route.json")).unwrap(); + for locale in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + for id in [ + "render.glass_library_conflict", + "render.glass_library_edit", + "render.glass_library_help", + "render.glass_library_method", + "render.glass_library_prepared", + ] { + assert!(messages[locale][id].as_str().is_some_and(|s| !s.is_empty()), "{locale}/{id}"); + } + } + } +} + +#[test] +fn cpu_partial_coverage_crosses_u16_boundary_without_relaxing_alpha_or_sample_frontier() { + for count in [65_535, 65_536, 1_048_576] { + assert!(interactive::validate_partial_pixel(count, count, Color32::BLACK, [40, 80, 120]).is_ok()); + assert!(interactive::validate_partial_pixel(count, count + 1, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(count, count, Color32::TRANSPARENT, [40, 80, 120]).is_err()); + assert_eq!(interactive::partial_sample_count(count, 0, 0, 1, 1_048_576).unwrap(), count); + } + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(65_536, 0, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(65_536, 0, Color32::from_rgb(40, 80, 120), [40, 80, 120]).is_ok()); + assert!(interactive::partial_sample_count(65_536, 1, 0, 1, 65_536).is_err()); +} + +#[test] +fn cpu_progressive_editor_preserves_high_intent_without_resizing_or_changing_profile_seed_or_mode() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Workstation; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: u32::MAX }); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + for budget in [CpuBudget::Workstation, CpuBudget::Compact, CpuBudget::Studio] { + h.app.render_workspace.view.raytrace.budget = budget; + let before = json!(h.app.render_workspace.view.raytrace); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(cpu::progressive_controls(&mut h.app, ui)); + }); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before, "painting cannot clamp retained intent to a different profile"); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1, 1)); + assert_eq!(cpu::validate_progressive_image(&h.app).is_ok(), budget == CpuBudget::Workstation); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); +} + +// Request/consumer coverage only. Real native per-pass presentation remains +// mandatory acceptance; see the archived unsupported cooperative-host fixture. +#[test] +fn cpu_progressive_request_keeps_explicit_target_seed_without_claiming_native_pass_presentation() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 741 }); + let document = h.app.session.doc.clone(); + let before = json!(h.app.render_workspace.view.raytrace); + let request = interactive_request(&h.app).unwrap(); + assert_eq!(request["raytrace"]["progressive"]["samples_per_pixel"], 4); + assert_eq!(request["raytrace"]["progressive"]["seed"], 741); + assert_ne!(request["progressive"], json!(true), "CPU intent cannot select a registered GPU executor"); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation() { + use solidcraft_engine::render::job::{CpuProgressiveOptions, Phase}; + use std::{sync::mpsc, time::Duration}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation") { + return; + } + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); + let before = json!(h.app.render_workspace.view.raytrace); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + // Withhold only the real worker reply. All frame bytes come from the renderer. + let mut pending = h.app.render_workspace.interactive.pending.take().unwrap(); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).unwrap(); + assert!(matches!(&reply, Ok(true)), "{reply:?}"); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 })); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert!(!frame.png().is_empty()); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + sender.send(reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, samples, complete), (job.id(), 31, true)); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + let egui::ImageData::Color(pixels) = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 47, seed: 999 }); + let expected = crate::i18n::format("render.interactive_samples", &[("done", "31"), ("total", "31")]); + let controls = h.ctx.run_ui(egui::RawInput::default(), |ui| interactive::controls(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&controls).any(|shape| shape.galley.text() == expected)); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_retention_skip_inspect_is_null_without_an_admitted_capture() { + let h = Harness::new(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off() { + let mut h = interactive_ui_fixture(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); + if !interactive_test_cpu_branch(&mut h, "interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off") { + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null(), "enabling without an admitted job cannot fabricate zero"); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let captured = held.job.status().unwrap(); + assert_eq!(captured.cpu_preview_retention_skips, 0); + assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(captured.cpu_preview_retention_skips)); + interactive_assert_final_export_isolation(&mut h, &held.job); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(0)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); +} + +// Typed consumer state only: this texture is input to the absent-slot policy. +// It is not a renderer PNG, a CPU admission fixture, or per-pass UI acceptance. +fn cpu_preview_consumer_fixture(ctx: &egui::Context) -> (State, JobId, solidcraft_engine::render::job::JobStatus) { + use solidcraft_engine::render::job::{ + AlphaConvention, ColourEncoding, CpuProgressiveOptions, FrameInfo, ImageRequest, JobOptions, JobStatus, Phase, Progress, RaytraceOptions, + }; + use solidcraft_engine::render::{BackendId, ExecutorId, RenderMode, RenderOperation, RenderProfile, ResolvedRequest}; + let job = JobId { session: 9012, serial: 1, generation: 1 }; + let backend = BackendId::new("consumer-fixture").unwrap(); + let executor = ExecutorId::new("consumer-fixture").unwrap(); + let frame = FrameInfo { + job, + scene_generation: 19, + backend: backend.clone(), + executor: executor.clone(), + width: 1, + height: 1, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: 0, + png_sha256: String::new(), + }; + let texture = + ctx.load_texture("consumer-only-input", egui::ColorImage::new([1, 1], vec![Color32::from_rgb(40, 80, 120)]), egui::TextureOptions::LINEAR); + let mut state = State::default(); + state.view.job = Some(job); + state.preview_image = Some(PreviewImage { info: PreviewInfo { frame_sequence: 2, samples_per_pixel: 2, frame }, image: Ok(texture) }); + let request = ImageRequest { + raster_exposure_ev: 0.0, + raster_lights: None, + raster_punctual_lights: None, + raster_area_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + primary_samples: 1, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 7, seed: 741 }), + ..Default::default() + }), + camera: Default::default(), + width: 1, + height: 1, + background: [40, 80, 120], + transparent_background: false, + }; + let status = JobStatus { + cpu_preview_retention_skips: 1, + punctual_diagnostics: None, + presentation: None, + sampling: None, + linear_master: None, + preview: None, + textures: None, + options: JobOptions::default(), + environment: None, + job, + scene_generation: 19, + request, + resolved: ResolvedRequest { + backend, + executor, + profile: RenderProfile { mode: RenderMode::Preview, operation: RenderOperation::Image, formats: Vec::new(), features: Vec::new() }, + width: 1, + height: 1, + format: None, + estimated_scratch_bytes: 0, + warnings: Vec::new(), + }, + progress: Progress { phase: Phase::Running, done: 3, total: 7 }, + error: None, + frame: None, + }; + (state, job, status) +} + +#[test] +fn cpu_missing_snapshot_consumer_keeps_exact_pixels_identity_and_pass_only_for_certified_live_capture() { + let ctx = egui::Context::default(); + let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); + let before = state.preview_image.as_ref().unwrap(); + let texture = before.image.as_ref().unwrap().id(); + let identity = (before.info.frame.job, before.info.frame.scene_generation, before.info.frame_sequence, before.info.samples_per_pixel); + status.progress.done = 4; + reconcile_missing_cpu_preview(&mut state, job, Some(&status)); + let kept = state.preview_image.as_ref().unwrap(); + assert_eq!(kept.image.as_ref().unwrap().id(), texture); + assert_eq!((kept.info.frame.job, kept.info.frame.scene_generation, kept.info.frame_sequence, kept.info.samples_per_pixel), identity); + assert_eq!(kept.info.samples_per_pixel, 2, "producer progress cannot relabel accepted pixels"); + assert!(state.view.completed.is_none(), "retention cannot manufacture final authority"); +} + +#[test] +fn cpu_missing_snapshot_consumer_clears_wrong_capture_cancel_error_final_and_lookup_failure() { + use solidcraft_engine::render::job::{ErrorCode, JobError, Phase}; + let ctx = egui::Context::default(); + for case in 0..13 { + let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); + let mut lookup_ok = true; + match case { + 0 => status.job.serial += 1, + 1 => status.scene_generation += 1, + 2 => status.request.width += 1, + 3 => status.progress.phase = Phase::Cancelling, + 4 => status.progress.phase = Phase::Cancelled, + 5 => status.progress.phase = Phase::Failed, + 6 => status.progress.phase = Phase::Completed, + 7 => status.error = Some(JobError::new(ErrorCode::Internal, "consumer fixture status error")), + 8 => status.frame = Some(state.preview_image.as_ref().unwrap().info.frame.clone()), + 9 => status.cpu_preview_retention_skips = 0, + 10 => status.request.raytrace.as_mut().unwrap().progressive = None, + 11 => state.preview_image.as_mut().unwrap().image = Err("consumer fixture decode error".into()), + 12 => lookup_ok = false, + _ => unreachable!(), + } + reconcile_missing_cpu_preview(&mut state, job, lookup_ok.then_some(&status)); + assert!(state.preview_image.is_none(), "case {case}"); + assert!(state.view.completed.is_none()); + } + let mut h = Harness::new(); + let (mut state, job, _) = cpu_preview_consumer_fixture(&ctx); + state.view.job = None; + h.app.render_workspace = state; + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + let (state, _, _) = cpu_preview_consumer_fixture(&ctx); + h.app.render_workspace = state; + assert!(h.app.session.render_job_handle(job).is_err(), "consumer fixture is deliberately not an admitted job"); + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/delta-LF-review.patch b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/delta-LF-review.patch new file mode 100644 index 000000000..ee6a0b13e --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/delta-LF-review.patch @@ -0,0 +1,10 @@ +--- a/crates/ui-egui/src/render_workspace_tests.rs ++++ b/crates/ui-egui/src/render_workspace_tests.rs +@@ -11335,6 +11335,7 @@ + h.app.render_workspace.view.raytrace.budget = budget; + let before = json!(h.app.render_workspace.view.raytrace); + let ctx = egui::Context::default(); ++ crate::fonts::setup_bundled_fonts(&ctx); + let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(cpu::progressive_controls(&mut h.app, ui)); + }); diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/source-bindings.json b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/source-bindings.json new file mode 100644 index 000000000..8b64d4dfc --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/fontfix/source-bindings.json @@ -0,0 +1,18 @@ +{ + "status": "SOURCE_ONLY_NOT_ADOPTED_UNCOMPILED_UNRUN", + "subpackage": "fontfix", + "base_source_manifest_sha256": "d38a8d946b6653864ad8918d4da662725bd24ca01b2e5aa2d3b38b47b1a7e163", + "base_rule": "Exact per-file RAW preimages only. Not current main, not a combined candidate. LF patch is review aid; RAW candidate bytes are authoritative.", + "files": [ + { + "path": "crates/ui-egui/src/render_workspace_tests.rs", + "before_sha256": "28ddafe4a8f133c522ddf6f1e0eaaaf70f954d7b8acdb7cca44aabef9a512e47", + "before_bytes": 634699, + "after_sha256": "9a3e58d83f6180ef8cd89c36a4ae4a8d09679f23a15f222a95edc2b70db25e9c", + "after_bytes": 634748 + } + ], + "full_CI_native_or_readiness": false, + "candidate_whole_file_overlay_safe": false, + "shared_before_test_file_sha256": "28ddafe4a8f133c522ddf6f1e0eaaaf70f954d7b8acdb7cca44aabef9a512e47" +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/README.md b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/README.md new file mode 100644 index 000000000..5ea63d738 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/README.md @@ -0,0 +1,14 @@ +# Preference UI and locale successor WIP + +Two RAW candidates: prefs.rs from the sealed preferences proposal and the exact +locale-only v2 successor. **NOT ADOPTED, UNCOMPILED, UNRUN**. One new preference +contract test is written, not executed. Both bools default true, persist through +the existing typed protocol, reject nonboolean values and reset with Graphics. +Unrelated page reset preserves them. The collapsed Advanced CPU rendering +section uses existing UI-kit controls. Runtime consumers require core + ui. + +The locale successor changes one help message in six languages, describing the +earlier sparse policy without promising powers-of-two for protected rendering. +Publication can be coalesced by the display; no physical-repaint guarantee is +made. Other message values remain exact. The new locale has no original base +file; the intermediate v1 hash is recorded only as lineage in the bindings. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/candidate/assets/locales/pending/cpu-progressive-policy-preferences.json b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/candidate/assets/locales/pending/cpu-progressive-policy-preferences.json new file mode 100644 index 000000000..6da009d40 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/candidate/assets/locales/pending/cpu-progressive-policy-preferences.json @@ -0,0 +1,44 @@ +{ + "de": { + "prefs.cpu_render_advanced": "Erweitertes CPU-Rendering", + "prefs.render_cpu_interactive_explicit_sampling": "Erfasste progressive Abtastung in Interactive verwenden", + "prefs.render_cpu_interactive_explicit_sampling_help": "Verwendet das erfasste Abtastziel und den Zufallsstartwert. Aus stellt nur für Interactive 16 Abtastungen und Startwert 0 wieder her. Ohne progressive Anfrage bleibt 16/0; finale Einstellungen bleiben unverändert.", + "prefs.render_cpu_progressive_every_pass": "Jeden vollständigen CPU-Durchgang veröffentlichen", + "prefs.render_cpu_progressive_every_pass_help": "Veröffentlicht jeden vollständigen nichtfinalen Durchgang bei verfügbarem Snapshot-Speicher. Aus stellt die frühere sparsame Rückmeldung wieder her. Das Ziel bleibt gleich; die Anzeige kann Aktualisierungen zusammenfassen." + }, + "en": { + "prefs.cpu_render_advanced": "Advanced CPU rendering", + "prefs.render_cpu_interactive_explicit_sampling": "Use captured progressive sampling in Interactive", + "prefs.render_cpu_interactive_explicit_sampling_help": "Use the captured progressive target and seed. Off restores 16 samples and seed 0 for Interactive only. An absent progressive request still uses 16/0; final settings are unchanged.", + "prefs.render_cpu_progressive_every_pass": "Publish every complete CPU pass", + "prefs.render_cpu_progressive_every_pass_help": "Publish each complete nonfinal pass when snapshot storage is available. Off restores the earlier sparse feedback policy. The target is unchanged; the screen may combine updates." + }, + "es": { + "prefs.cpu_render_advanced": "Renderizado CPU avanzado", + "prefs.render_cpu_interactive_explicit_sampling": "Usar el muestreo progresivo capturado en Interactive", + "prefs.render_cpu_interactive_explicit_sampling_help": "Usa el objetivo y la semilla progresivos capturados. Desactivado restaura 16 muestras y semilla 0 solo en Interactive. Sin petición progresiva se conserva 16/0; los ajustes finales no cambian.", + "prefs.render_cpu_progressive_every_pass": "Publicar cada pasada CPU completa", + "prefs.render_cpu_progressive_every_pass_help": "Publica cada pasada completa no final cuando hay espacio para snapshots. Desactivado restaura la política anterior de actualizaciones espaciadas. El objetivo no cambia; la pantalla puede agrupar actualizaciones." + }, + "ja": { + "prefs.cpu_render_advanced": "CPUレンダリングの詳細設定", + "prefs.render_cpu_interactive_explicit_sampling": "Interactiveで取得済みのプログレッシブ設定を使用", + "prefs.render_cpu_interactive_explicit_sampling_help": "取得済みの目標サンプル数とシードを使用します。オフではInteractiveのみ16サンプル、シード0に戻ります。プログレッシブ指定がない場合は16/0を維持し、最終設定は変わりません。", + "prefs.render_cpu_progressive_every_pass": "CPUの各完了パスを公開", + "prefs.render_cpu_progressive_every_pass_help": "スナップショット用の空きがある場合、最終以外の各完了パスを公開します。オフでは以前の間隔を空けた更新方針に戻ります。目標は変わらず、画面更新はまとめられる場合があります。" + }, + "ko": { + "prefs.cpu_render_advanced": "고급 CPU 렌더링", + "prefs.render_cpu_interactive_explicit_sampling": "Interactive에서 캡처한 점진적 샘플링 사용", + "prefs.render_cpu_interactive_explicit_sampling_help": "캡처한 샘플 목표와 시드를 사용합니다. 끄면 Interactive만16샘플과 시드0으로 돌아갑니다. 점진적 요청이 없으면16/0을 유지하며 최종 설정은 바뀌지 않습니다.", + "prefs.render_cpu_progressive_every_pass": "완료된 CPU 패스마다 게시", + "prefs.render_cpu_progressive_every_pass_help": "스냅샷 공간이 있으면 마지막을 제외한 각 완료 패스를 게시합니다. 끄면 이전의 간헐적 피드백 정책으로 돌아갑니다. 목표는 그대로이며 화면 업데이트가 합쳐질 수 있습니다." + }, + "zh": { + "prefs.cpu_render_advanced": "高级CPU渲染", + "prefs.render_cpu_interactive_explicit_sampling": "在Interactive中使用已捕获的渐进采样设置", + "prefs.render_cpu_interactive_explicit_sampling_help": "使用已捕获的采样目标和种子。关闭后,仅Interactive恢复为16个样本和种子0。未指定渐进请求时仍使用16/0;最终设置不变。", + "prefs.render_cpu_progressive_every_pass": "发布每个完整的CPU遍次", + "prefs.render_cpu_progressive_every_pass_help": "快照空间可用时,发布最终遍次之前的每个完整遍次。关闭后恢复之前间隔更新的策略。目标不变;屏幕可能合并更新。" + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/candidate/crates/ui-egui/src/prefs.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/candidate/crates/ui-egui/src/prefs.rs new file mode 100644 index 000000000..d881a9cd7 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/candidate/crates/ui-egui/src/prefs.rs @@ -0,0 +1,6840 @@ +//! Grouped preferences composed with the shared UI kit. Changes apply immediately; Cancel +//! restores the opening snapshot, Apply keeps editing, and Defaults affects the current page. + +use egui::{Modifiers, Pos2}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +pub use solidcraft_engine::doc::display_units::{format_length, length_number, length_precision, unit_scale}; +use solidcraft_engine::geom::Vec3; +use solidcraft_engine::render::Camera; + +/// The key the apps keep the preferences under in eframe's storage. +pub const STORAGE_KEY: &str = "solidcraft.prefs"; +/// The key earlier releases used. Compatibility shim (docs/compatibility.md): read when the +/// current key is missing, never written. +pub const LEGACY_STORAGE_KEY: &str = "solvecraft.prefs"; + +/// The stored preferences, from the current key or else the legacy one. +pub fn stored(get: impl Fn(&str) -> Option) -> Option { + get(STORAGE_KEY).or_else(|| get(LEGACY_STORAGE_KEY)) +} + +mod design; +mod general; +mod graphics; +mod interface; +mod navbar; +mod navigation; +mod sketch; + +use crate::SolveApp; +use crate::theme::Tokens; +use crate::tool_modifiers::ModifierCombo; +use crate::ui_kit; +use crate::viewport::NavMode; + +pub const UNITS: &[&str] = &["mm", "cm", "m", "in", "ft"]; +pub const OPENSCAD_NAV: &str = "openscad"; +pub const TOUCHPAD_NAV: &str = "touchpad"; +/// A mouse button that can drag the camera. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NavButton { + Left, + Middle, + Right, +} + +/// Modifier keys a binding needs held (others may be held too). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct NavKeys { + pub shift: bool, + pub ctrl: bool, + pub alt: bool, +} + +impl NavKeys { + const NONE: NavKeys = NavKeys { shift: false, ctrl: false, alt: false }; + const SHIFT: NavKeys = NavKeys { shift: true, ctrl: false, alt: false }; + const CTRL: NavKeys = NavKeys { shift: false, ctrl: true, alt: false }; + const ALT: NavKeys = NavKeys { shift: false, ctrl: false, alt: true }; + const SHIFT_ALT: NavKeys = NavKeys { shift: true, ctrl: false, alt: true }; + + /// All of these keys are held (Ctrl is Cmd on macOS). + fn held(self, m: Modifiers) -> bool { + (!self.shift || m.shift) && (!self.ctrl || m.ctrl || m.command) && (!self.alt || m.alt) + } +} + +/// One camera binding: dragging `button` with `keys` held does `mode`. +#[derive(Clone, Copy, Debug)] +pub struct NavBinding { + pub button: NavButton, + pub keys: NavKeys, + pub mode: NavMode, +} + +const fn bind(button: NavButton, keys: NavKeys, mode: NavMode) -> NavBinding { + NavBinding { button, keys, mode } +} + +/// A mouse mapping: its bindings, most specific first (the first one whose button is dragged +/// with all its keys held wins). +pub struct NavPreset { + pub id: &'static str, + pub label: &'static str, + /// What the mouse does, for the Preferences page. + pub help: &'static str, + /// Choosing the preset turns the wheel the other way. + pub reverse_zoom: bool, + /// Choosing the preset sets what a middle double-click does (`None` leaves it as it is). + pub middle_double_click: Option<&'static str>, + /// Choosing the preset sets "Right drag orbits" (`None` leaves it as it is). + pub right_drag_orbits: Option, + pub bindings: &'static [NavBinding], +} + +impl NavPreset { + /// What dragging `button` with `mods` held does, if anything. + pub fn mode(&self, button: NavButton, mods: Modifiers) -> Option { + self.bindings.iter().find(|b| b.button == button && b.keys.held(mods)).map(|b| b.mode) + } +} + +use NavButton::{Left, Middle, Right}; +use NavMode::{Orbit, Pan, Zoom}; + +/// The mouse mappings. The first is the default. +pub const NAV_PRESETS: &[NavPreset] = &[ + NavPreset { + id: "fusion", + label: "Fusion", + help: "Middle drag pans, Shift+middle orbits, right drag orbits", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[bind(Middle, NavKeys::SHIFT, Orbit), bind(Middle, NavKeys::NONE, Pan), bind(Right, NavKeys::NONE, Orbit)], + }, + NavPreset { + id: "solidworks", + label: "SolidWorks", + help: "Middle drag orbits, Ctrl+middle pans, Shift+middle zooms, right drag orbits", + reverse_zoom: true, + // Picked here, the right button is left to the context menu and mouse gestures (#6492). + middle_double_click: Some("fit"), + right_drag_orbits: Some(false), + bindings: &[ + bind(Middle, NavKeys::CTRL, Pan), + bind(Middle, NavKeys::SHIFT, Zoom), + bind(Middle, NavKeys::NONE, Orbit), + bind(Right, NavKeys::NONE, Orbit), + ], + }, + NavPreset { + id: "inventor", + label: "Inventor", + help: "Middle drag pans, Shift+middle orbits, Ctrl+middle zooms, right drag orbits", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[ + bind(Middle, NavKeys::SHIFT, Orbit), + bind(Middle, NavKeys::CTRL, Zoom), + bind(Middle, NavKeys::NONE, Pan), + bind(Right, NavKeys::NONE, Orbit), + ], + }, + NavPreset { + id: "alias", + label: "Alias", + help: "Shift+Alt+left drag orbits, Shift+Alt+middle pans, Shift+Alt+right zooms; middle drag also pans and right drag orbits", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[ + bind(Left, NavKeys::SHIFT_ALT, Orbit), + bind(Middle, NavKeys::SHIFT_ALT, Pan), + bind(Right, NavKeys::SHIFT_ALT, Zoom), + bind(Middle, NavKeys::CTRL, Zoom), + bind(Middle, NavKeys::NONE, Pan), + bind(Right, NavKeys::NONE, Orbit), + ], + }, + NavPreset { + id: "maya", + label: "Maya", + help: "Alt+left drag orbits, Alt+middle pans, Alt+right zooms; middle drag also pans", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[ + bind(Left, NavKeys::ALT, Orbit), + bind(Middle, NavKeys::ALT, Pan), + bind(Right, NavKeys::ALT, Zoom), + bind(Middle, NavKeys::NONE, Pan), + ], + }, + NavPreset { + id: "blender", + label: "Blender", + help: "Middle drag orbits, Shift+middle pans, Ctrl+middle zooms; right drag leaves the camera alone", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[bind(Middle, NavKeys::SHIFT, Pan), bind(Middle, NavKeys::CTRL, Zoom), bind(Middle, NavKeys::NONE, Orbit)], + }, + NavPreset { + id: "tinkercad", + label: "Tinkercad", + help: "Right drag orbits, middle or Shift+right drag pans", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[bind(Right, NavKeys::SHIFT, Pan), bind(Right, NavKeys::NONE, Orbit), bind(Middle, NavKeys::NONE, Pan)], + }, + NavPreset { + id: OPENSCAD_NAV, + label: "OpenSCAD", + help: "Left drag on empty space orbits, Shift+left drag box-selects, sketch geometry drags edit; right or middle drag pans, Shift+right or Shift+middle drag zooms", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[ + bind(Left, NavKeys::NONE, Orbit), + bind(Right, NavKeys::SHIFT, Zoom), + bind(Middle, NavKeys::SHIFT, Zoom), + bind(Right, NavKeys::NONE, Pan), + bind(Middle, NavKeys::NONE, Pan), + ], + }, + NavPreset { + id: "hfss", + label: "HFSS", + help: "Alt+left drag pans, Shift+Alt+left zooms, Ctrl+left drag on empty space orbits", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + // Ctrl+left orbit is the drag from empty space every preset has: as a binding it would + // also take a Ctrl+click on geometry, which adds to the selection. + bindings: &[bind(Left, NavKeys::SHIFT_ALT, Zoom), bind(Left, NavKeys::ALT, Pan)], + }, + NavPreset { + id: TOUCHPAD_NAV, + label: "Touchpad", + help: "Hold Shift and move the pointer to pan; hold Alt/Option and move it to orbit. No mouse button is needed. Vertical scroll zooms.", + reverse_zoom: false, + middle_double_click: None, + right_drag_orbits: None, + bindings: &[bind(Middle, NavKeys::NONE, Pan), bind(Right, NavKeys::NONE, Orbit)], + }, +]; + +impl NavPreset { + /// Button-free motion has exact modifiers, unlike the additive drag bindings. + pub fn motion_mode(&self, mods: Modifiers) -> Option { + if self.id != TOUCHPAD_NAV || mods.ctrl || mods.command || mods.mac_cmd { + return None; + } + match (mods.shift, mods.alt) { + (true, false) => Some(Pan), + (false, true) => Some(Orbit), + _ => None, + } + } + + pub(crate) fn translated_label(&self) -> &str { + if self.id == TOUCHPAD_NAV { crate::i18n::tr("nav.touchpad.label") } else { crate::i18n::tr_label(self.label) } + } +} + +impl Prefs { + /// Touchpad scroll zooms without overwriting the user's preference for other presets. + pub fn trackpad_pans(&self) -> bool { + self.nav != TOUCHPAD_NAV && self.trackpad_pan + } +} + +/// The preset with this id (the default for an unknown one). +pub fn nav_preset(id: &str) -> &'static NavPreset { + NAV_PRESETS.iter().find(|p| p.id == id).unwrap_or(&NAV_PRESETS[0]) +} + +/// Picks `preset` the way the Preferences page does: its bindings, wheel direction and, when the +/// preset names them, middle double-click and "Right drag orbits". +pub fn choose_nav_preset(prefs: &mut Prefs, preset: &NavPreset) { + prefs.nav = preset.id.into(); + prefs.zoom_reverse = preset.reverse_zoom; + if let Some(double_click) = preset.middle_double_click { + prefs.middle_double_click = double_click.into(); + } + if let Some(orbits) = preset.right_drag_orbits { + prefs.right_drag_orbits = orbits; + } +} +/// Stable control-channel names; presentation labels may be shorter. +pub const PAGES: &[&str] = &["General", "Interface", "Design", "Navigation", "Keyboard Shortcuts", "Sketch", "Graphics", "AI", "Plugins"]; +pub const PAGE_GENERAL: usize = 0; +pub const PAGE_INTERFACE: usize = 1; +pub const PAGE_DESIGN: usize = 2; +pub const PAGE_NAVIGATION: usize = 3; +pub const PAGE_SHORTCUTS: usize = 4; +pub const PAGE_SKETCH: usize = 5; +pub const PAGE_GRAPHICS: usize = 6; +pub const PAGE_AI: usize = 7; +pub const PAGE_PLUGINS: usize = 8; +const WINDOW_PAGES: &[ui_kit::WindowPage] = &[ + ui_kit::WindowPage { icon: "settings", label: "ui.general", group: None, handle: "prefs:page:General", scroll: true, draw: window_page::<0> }, + ui_kit::WindowPage { + icon: "settings_palette", + label: "prefs.interface", + group: None, + handle: "prefs:page:Interface", + scroll: true, + draw: window_page::<1>, + }, + ui_kit::WindowPage { icon: "ws_design", label: "ui.design", group: None, handle: "prefs:page:Design", scroll: true, draw: window_page::<2> }, + ui_kit::WindowPage { + icon: "settings_mouse", + label: "ui.navigation", + group: Some("prefs.input"), + handle: "prefs:page:Navigation", + scroll: true, + draw: window_page::<3>, + }, + ui_kit::WindowPage { + icon: "settings_keyboard", + label: "prefs.shortcuts", + group: None, + handle: "prefs:page:Keyboard Shortcuts", + scroll: false, + draw: window_page::<4>, + }, + ui_kit::WindowPage { + icon: "sketch", + label: "prefs.sketch_selection", + group: None, + handle: "prefs:page:Sketch", + scroll: true, + draw: window_page::<5>, + }, + ui_kit::WindowPage { + icon: "settings_monitor", + label: "ui.graphics", + group: Some("prefs.display"), + handle: "prefs:page:Graphics", + scroll: true, + draw: window_page::<6>, + }, + ui_kit::WindowPage { + icon: "assistant", + label: "prefs.assistant", + group: Some("prefs.extend"), + handle: "prefs:page:AI", + scroll: true, + draw: window_page::<7>, + }, + ui_kit::WindowPage { + icon: "settings_plug", + label: "ui.plugins", + group: None, + handle: "prefs:page:Plugins", + scroll: true, + draw: window_page::<8>, + }, +]; + +fn search_header(ui: &mut egui::Ui, app: &mut SolveApp) { + let typed = drive_search(ui, app); + let (field, _) = + ui_kit::search_actions_row(ui, egui::Id::new("prefs_search"), &mut app.prefs_window.filter, crate::i18n::tr("prefs.search"), &[]); + if typed { + place_search_cursor(ui.ctx(), egui::Id::new("prefs_search"), app.prefs_window.filter.chars().count()); + } + crate::scenario::publish_handle("prefs:search", field.rect.center()); + if field.has_focus() { + crate::prefs_search::note_key_sink(ui.ctx()); + } + settle_search(app); + crate::prefs_search::set_reveal(ui.ctx(), app.prefs_window.reveal.clone()); + crate::prefs_search::set_force_scroll(ui.ctx(), !app.prefs_window.filter.trim().is_empty()); + ui.add_space(Tokens::get().space_8); +} + +/// Keys for the search field. Shortcut capture keeps the key for itself. +fn drive_search(ui: &mut egui::Ui, app: &mut SolveApp) -> bool { + let ctx = ui.ctx().clone(); + if crate::keymap::capturing(app) { + return false; + } + let id = egui::Id::new("prefs_search"); + if ctx.input_mut(|input| input.consume_key(egui::Modifiers::COMMAND, egui::Key::F)) { + ctx.memory_mut(|memory| memory.request_focus(id)); + } + let sink = crate::prefs_search::key_sink(&ctx); + let mut typed = false; + if !sink { + let modifiers = ctx.input(|input| input.modifiers); + if !modifiers.command && !modifiers.ctrl && !modifiers.alt { + let mut chars = String::new(); + ctx.input_mut(|input| { + input.events.retain(|event| { + let egui::Event::Text(text) = event else { return true }; + if text.chars().any(char::is_control) { + return true; + } + chars.push_str(text); + false + }); + }); + if !chars.is_empty() { + app.prefs_window.filter.push_str(&chars); + ctx.memory_mut(|memory| memory.request_focus(id)); + typed = true; + } + } + } + let query = app.prefs_window.filter.trim().to_lowercase(); + if query.is_empty() { + return typed; + } + let (nav_query, cursor, hits) = crate::prefs_search::nav(&ctx); + let fresh = nav_query == query; + let cursor = if fresh { cursor.min(hits.len().saturating_sub(1)) } else { 0 }; + if ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)) && fresh && !hits.is_empty() { + crate::prefs_search::set_cursor(&ctx, (cursor + 1).min(hits.len() - 1)); + } else if ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)) && fresh && !hits.is_empty() { + crate::prefs_search::set_cursor(&ctx, cursor.saturating_sub(1)); + } else if fresh && !hits.is_empty() && ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + if let Some(hit) = hits.get(cursor) { + open_result(app, hit.page, &hit.label); + ctx.memory_mut(|memory| memory.surrender_focus(id)); + } + } else { + crate::prefs_search::set_cursor(&ctx, cursor); + } + if !app.prefs_window.filter.trim().is_empty() && ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + app.prefs_window.filter.clear(); + ctx.memory_mut(|memory| memory.surrender_focus(id)); + } + typed +} + +fn place_search_cursor(ctx: &egui::Context, id: egui::Id, chars: usize) { + let Some(mut state) = egui::TextEdit::load_state(ctx, id) else { return }; + let cursor = egui::text::CCursor::new(chars); + state.cursor.set_char_range(Some(egui::text::CCursorRange::one(cursor))); + state.store(ctx, id); +} + +fn open_result(app: &mut SolveApp, page: usize, label: &str) { + app.prefs_window.filter.clear(); + app.prefs_window.search_from = None; + app.prefs_window.section = page; + app.prefs_window.land_on = Some(page); + app.prefs_window.reveal = Some(crate::prefs_search::reveal_for(page, label)); +} + +/// An empty field returns to the page that was up when the search started. +fn settle_search(app: &mut SolveApp) { + if app.prefs_window.filter.trim().is_empty() { + if app.prefs_window.reveal.is_none() + && let Some(page) = app.prefs_window.search_from.take() + { + app.prefs_window.section = page; + app.prefs_window.land_on = Some(page); + } + } else if app.prefs_window.search_from.is_none() { + app.prefs_window.search_from = Some(app.prefs_window.section); + } +} + +/// A page tab leaves search and shows that page on its own. +fn clear_search(app: &mut SolveApp) { + app.prefs_window.filter.clear(); + app.prefs_window.search_from = None; + app.prefs_window.reveal = None; +} + +fn window_page(ui: &mut egui::Ui, app: &mut SolveApp) { + if let Some(rect) = crate::scenario::rect_of("prefs:page:Sketch") { + crate::scenario::publish_target("prefs:page:Selection", rect); + } + if let Some(page) = app.prefs_window.land_on.take() { + if app.prefs_window.section != page { + crate::keymap::stop_capture(app); + app.keymap.read_only = false; + } + app.prefs_window.section = page; + } else if app.prefs_window.section != INDEX { + crate::keymap::stop_capture(app); + app.keymap.read_only = false; + app.prefs_window.section = INDEX; + } + page(app, ui, &Tokens::get()); +} + +pub const THEMES: &[(&str, &str)] = &[("dark", "Dark"), ("light", "Light"), ("system", "System")]; +pub const MSAA: [u32; 4] = [1, 2, 4, 8]; +/// Supersampling factors (#1288): off, 1.5× and 2× the viewport's pixels each way. +pub const SUPERSAMPLING: [f32; 3] = [1.0, 1.5, 2.0]; + +/// Original view navigators, independent of the mouse navigation preset. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NavigatorStyle { + /// Also what a navigator this version doesn't know reads as (`lenient`). + #[default] + Axes, + Cube, +} + +impl NavigatorStyle { + pub const ALL: [Self; 2] = [Self::Axes, Self::Cube]; + + pub fn label(self) -> &'static str { + match self { + Self::Axes => "Signed axes", + Self::Cube => "Cube", + } + } +} + +/// How the History at the left lists sketches (Preferences: "Sketches", #6489). The timeline +/// along the bottom always keeps the creation order. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HistorySketches { + /// Every sketch is a row of its own, in creation order (how it always was). Also what a + /// value this version doesn't know reads as (`lenient`). + #[default] + InOrder, + /// A sketch a feature is built from is listed one level in, under that feature. + UnderFeature, +} + +/// What the interface calls the origin planes (Preferences › Interface). Only the names shown +/// change: the planes' ids (`XY`, `XZ`, `YZ`), commands, scripts and saved designs keep theirs. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OriginPlaneNames { + /// XY, XZ and YZ. Also what a naming this version doesn't know reads as (`lenient`). + #[default] + Xyz, + /// Top for XY, Front for XZ and Right for YZ (Z up), the engine's aliases for them. + TopFrontRight, +} + +impl OriginPlaneNames { + pub const ALL: [Self; 2] = [Self::Xyz, Self::TopFrontRight]; + /// The origin planes' ids, in the order the Preferences list them. + pub const PLANES: [&'static str; 3] = ["XY", "XZ", "YZ"]; + + /// The name shown for the plane `name`: an origin plane in this naming, in the interface's + /// language; any other plane (a construction plane) by its own name. + pub fn label(self, name: &str) -> &str { + match (self, name) { + (Self::TopFrontRight, "XY") => crate::i18n::tr("ui.top"), + (Self::TopFrontRight, "XZ") => crate::i18n::tr("ui.front"), + (Self::TopFrontRight, "YZ") => crate::i18n::tr("ui.right"), + _ => name, + } + } +} + +/// What an orbit turns around (Preferences: "Orbit around"). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OrbitAround { + /// The world origin: the view turns about it and keeps it still on screen. + Origin, + /// The view's centre: what Pan moves and Fit frames (the default, as it always was). + #[default] + ViewCentre, + /// The model point under the cursor when the drag began. + Cursor, +} + +/// The sole modifier that turns vertical scroll into wheel-style zoom. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TrackpadZoomModifier { + Cmd, + Alt, + Ctrl, + /// The default: scroll keeps its usual meaning until a key is chosen. + #[default] + Off, +} + +impl TrackpadZoomModifier { + pub const ALL: [Self; 4] = [Self::Cmd, Self::Alt, Self::Ctrl, Self::Off]; + + pub fn modifiers(self) -> Option { + match self { + Self::Cmd => Some(egui::Modifiers::COMMAND), + Self::Alt => Some(egui::Modifiers::ALT), + Self::Ctrl => Some(egui::Modifiers::CTRL), + Self::Off => None, + } + } + + pub fn label_id(self, platform: crate::tool_modifiers::Platform) -> &'static str { + match self { + Self::Cmd if platform == crate::tool_modifiers::Platform::Mac => "prefs.trackpad_zoom_modifier.cmd", + Self::Alt => "prefs.trackpad_zoom_modifier.alt", + Self::Cmd | Self::Ctrl => "prefs.trackpad_zoom_modifier.ctrl", + Self::Off => "prefs.trackpad_zoom_modifier.off", + } + } +} + +/// Where the view goes when a sketch ends (Preferences: "When a sketch ends", #7038). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SketchExitView { + /// Back to the view from before the sketch opened. + Previous, + /// The view stays where it is (the default since #4909). + #[default] + Keep, + /// Back to the view from before the sketch, unless the sketch view was turned: a view only + /// panned or zoomed goes back, a turned one stays. + UnlessRotated, +} + +impl SketchExitView { + pub const ALL: [Self; 3] = [Self::Previous, Self::Keep, Self::UnlessRotated]; + + /// The message id of the choice's label. + pub fn label_id(self) -> &'static str { + match self { + Self::Previous => "prefs.sketch_exit_view.previous", + Self::Keep => "prefs.sketch_exit_view.keep", + Self::UnlessRotated => "prefs.sketch_exit_view.unless_rotated", + } + } + + /// The view to turn to when a sketch ends with the camera at `now`, or `None` to leave it. + /// `before` is the view from before the sketch opened and `facing` the one it turned to then. + /// Going back keeps `now`'s projection, so a perspective switch made in the sketch stays. + pub fn view_after(self, before: Camera, facing: Camera, now: Camera) -> Option { + let back = Camera { fov: now.fov, ..before }; + match self { + Self::Previous => Some(back), + Self::Keep => None, + Self::UnlessRotated => same_orientation(facing, now).then_some(back), + } + } +} + +/// Whether two cameras look the same way: pans and zooms move a camera without turning it. +/// Half a degree absorbs rounding in the animation that turned the view to face the sketch. +fn same_orientation(a: Camera, b: Camera) -> bool { + let near = 0.5_f64.to_radians().cos(); + let ((ar, au, ab), (br, bu, bb)) = (a.basis(), b.basis()); + ar.dot(br) > near && au.dot(bu) > near && ab.dot(bb) > near +} + +/// How the offer to stand a file up is made when its header names no program known to save Y up +/// (Preferences: "For files from unknown programs", #7717). A file from SolidWorks is asked in the +/// dialog (only the note when it already stands on Z, unless this is Ask); SolidCraft's own files +/// are never offered. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StandUpUnknown { + /// The "Stand this part up?" dialog for every file from another program, without looking at + /// how it rests, as before #7717 (a SolidWorks file too). + Ask, + /// No offer: the context menu's Turn Up Axis still stands the file up. + Off, + /// A small note over the view, only when the file seems to lie on its back, that goes by + /// itself and never blocks input (the default). A saved value this version doesn't know reads + /// as this. + #[default] + #[serde(other)] + Note, +} + +impl StandUpUnknown { + pub const ALL: [Self; 3] = [Self::Ask, Self::Note, Self::Off]; + + /// The choice as `ui.prefs` and the saved preferences spell it. + pub fn id(self) -> &'static str { + match self { + Self::Ask => "ask", + Self::Note => "note", + Self::Off => "off", + } + } + + /// The message id of the choice's label. + pub fn label_id(self) -> &'static str { + match self { + Self::Ask => "prefs.stand_up_unknown.ask", + Self::Note => "prefs.stand_up_unknown.note", + Self::Off => "prefs.stand_up_unknown.off", + } + } +} + +/// Which program reads the 3D mouse on Linux when both spacenavd and the device itself (hidraw) +/// are there (Preferences: "3D mouse driver"). Read by the app's reader, not by this crate. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SpaceMouseDriver { + /// The device itself (hidraw) when it opens, else spacenavd. Spacenavd has been a known source of + /// trouble, and a device read directly keeps its settings across a replug. + #[default] + Automatic, + Spacenavd, + /// The hidraw device, bypassing spacenavd's settings. + Direct, +} + +/// Where the small 3D mouse picture sits in the 3D view (Preferences: "Position"). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SpaceMouseGhost { + /// The lower left corner of the viewport area, right of the browser (how it was first made). + /// Saved as `current` by the first build, which is still read. + #[default] + #[serde(alias = "current")] + LeftViewport, + /// The lower right corner of the viewport area. Saved as `right` by the first build. + #[serde(alias = "right")] + RightViewport, + /// The lower left corner of the whole window, under the browser. Saved as `left` by the first build. + #[serde(alias = "left")] + LeftWindow, +} + +impl SpaceMouseGhost { + pub const ALL: [Self; 3] = [Self::LeftViewport, Self::RightViewport, Self::LeftWindow]; +} + +impl SpaceMouseDriver { + pub const ALL: [Self; 3] = [Self::Automatic, Self::Spacenavd, Self::Direct]; + + /// The choice as the reader thread shares it (an `AtomicU8`). + pub fn to_u8(self) -> u8 { + self as u8 + } + + /// Back from [`Self::to_u8`]; anything else reads as Automatic. + pub fn from_u8(value: u8) -> Self { + Self::ALL.into_iter().find(|driver| driver.to_u8() == value).unwrap_or_default() + } +} + +/// The default largest STEP/import file, in MB (`solidcraft_io::MAX_STEP_BYTES`). +pub const DEFAULT_STEP_MB: u64 = solidcraft_engine::io::limits::FileLimits::DEFAULT.step / solidcraft_engine::io::limits::MB; +/// The default largest design file, in MB (`solidcraft_io::MAX_DESIGN_BYTES`). +pub const DEFAULT_DESIGN_MB: u64 = solidcraft_engine::io::limits::FileLimits::DEFAULT.design / solidcraft_engine::io::limits::MB; + +/// The file size limits the preferences ask for (Preferences › General › Largest file to open), +/// brought into range. +pub fn file_limits(p: &Prefs) -> solidcraft_engine::io::limits::FileLimits { + solidcraft_engine::io::limits::FileLimits::from_mb(p.max_step_file_mb, p.max_design_file_mb).clamped() +} + +/// Every read from now on uses the preferred file size limits (unless `--max-file-size` gave +/// this run its own). The browser keeps its defaults. +pub fn apply_file_limits(p: &Prefs) { + if solidcraft_engine::io::limits::ADJUSTABLE + && let Err(e) = solidcraft_engine::io::limits::set_preferred(file_limits(p)) + { + log::warn!("preferences: file size limits: {e}"); + } +} + +/// The browser sidebar's first width, and the width [`Prefs::default`] restores; the panel +/// itself clamps what the user drags to its own range. +pub const DEFAULT_BROWSER_WIDTH: f32 = 250.0; + +/// The browser's first share of the column it shares with History under it (#7371): the equal +/// split; the column clamps what the user drags so both cards keep their header and two rows. +pub const DEFAULT_BROWSER_SHARE: f32 = 0.5; + +/// When a component's bodies sit in a Bodies folder of their own in the browser (#4217): each +/// folder is one more level that pushes deep assemblies right. Only folders inside components +/// fold; the design's own Bodies folder, and a folder hidden with its eye (its eye is the way +/// back), always stay (`browser::bodies_folded`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BodiesFolders { + Always, + /// A component with one body and no groups lists the body straight under it. Also what a + /// value this version doesn't know reads as (`lenient`). + #[default] + Several, + /// Components list their bodies and groups straight under them. + Never, +} + +impl BodiesFolders { + pub const ALL: [Self; 3] = [Self::Always, Self::Several, Self::Never]; + + /// Its name in the Preferences (a message id). + pub fn label_id(self) -> &'static str { + match self { + Self::Always => "prefs.bodies_folders_always", + Self::Several => "prefs.bodies_folders_several", + Self::Never => "prefs.bodies_folders_never", + } + } +} + +// The stored fields, their defaults, page resets and simple form controls share this table. +// Omitted pages keep fields such as grid_follows_view and added agents when restoring defaults. +// Accepted control-channel ranges may differ from slider ranges (look_at_speed). +macro_rules! preference_settings { + ($( $(#[$doc:meta])* $field:ident: $ty:ty = $default:expr $(, $page:expr)? $(, accept($accepted:expr))? $(=> $control:ident($($args:tt)*))? ;)*) => { + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] + #[serde(default)] + pub struct Prefs { $($(#[$doc])* pub $field: $ty,)* } + + impl Default for Prefs { + fn default() -> Self { Self { $($field: $default,)* } } + } + + fn reset_preferences(p: &mut Prefs, page: usize) { + let d = Prefs::default(); + $($(if page == $page { p.$field = d.$field; })?)* + } + + mod accepted { + use super::*; + $($(pub(super) fn $field(p: &Prefs) -> bool { ($accepted).contains(&p.$field) })?)* + } + + mod setting { + use super::*; + $($(pub(super) fn $field(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response { + preference_settings!(@control app, ui, $field, $control($($args)*)) + })?)* + } + }; + (@control $app:ident, $ui:ident, $field:ident, check($label:literal $(, $help:literal)?)) => { + ui_kit::checkbox($ui, crate::i18n::tr_label($label), &mut $app.preferences.$field) + $(.on_hover_text(crate::i18n::tr_label($help)))? + }; + (@control $app:ident, $ui:ident, $field:ident, check_tr($label:literal)) => { + ui_kit::checkbox($ui, crate::i18n::tr($label), &mut $app.preferences.$field) + }; + (@control $app:ident, $ui:ident, $field:ident, check_id($label:literal)) => { + ui_kit::checkbox($ui, $app.tr($label), &mut $app.preferences.$field) + }; + (@control $app:ident, $ui:ident, $field:ident, number($label:literal, $range:expr)) => { + ui_kit::row($ui, $app.tr($label), |ui| { + ui_kit::number_field(ui, &mut $app.preferences.$field, $range, 1.0, "") + }) + }; + (@control $app:ident, $ui:ident, $field:ident, enabled_slider($enabled:ident, $label:literal, $range:expr, $step:expr, $format:expr)) => { + ui_kit::row($ui, $app.tr_label($label), |ui| { + ui.add_enabled_ui($app.preferences.$enabled, |ui| { + ui_kit::slider(ui, &mut $app.preferences.$field, $range, ui_kit::Slider { step: Some($step), format: $format, ..Default::default() }) + }).inner + }) + }; + (@control $app:ident, $ui:ident, $field:ident, slider($label:literal, $range:expr, $step:expr, $format:expr, $rect:literal)) => { + ui_kit::row($ui, $app.tr($label), |ui| { + let response = ui_kit::slider(ui, &mut $app.preferences.$field, $range, ui_kit::Slider { step: Some($step), format: $format, ..Default::default() }); + crate::scenario::publish_rect($rect, response.rect); + response + }) + }; +} + +preference_settings! { + /// Units of new designs. + default_units: String = "mm".into(), PAGE_DESIGN; + /// Mouse mapping: `fusion`, `solidworks` or `inventor`. + nav: String = "fusion".into(), PAGE_NAVIGATION; + /// Opt in to rotation through both poles with roll, without the Shift axis-snap spring. + /// Independent of mouse bindings; false also preserves existing saved presets' behavior. + free_orbit: bool = false, PAGE_NAVIGATION => check_tr("nav.free_orbit.label"); + /// With free orbit, mouse drags turn sideways about the world's up axis (a turntable without + /// the pole limit) instead of the screen's. + free_orbit_upright: bool = false, PAGE_NAVIGATION => check_tr("nav.free_orbit_upright.label"); + /// Off: a right drag that the mouse mapping would orbit leaves the camera alone (#6492). + right_drag_orbits: bool = true, PAGE_NAVIGATION => check_tr("nav.right_drag_orbits.label"); + /// View orientation widget: original signed axes (default) or compact cube. + navigator_style: NavigatorStyle = NavigatorStyle::default(), PAGE_NAVIGATION; + /// Show the radial ring and enable hold/flick gestures for viewport context menus. + radial_context_menu: bool = false, PAGE_NAVIGATION => check("Radial context menu"); + /// Work on the model directly in the viewport (pull a face to extrude or cut); off by default. + direct_interaction: bool = false, PAGE_NAVIGATION => check("Direct interaction", "Work on the model directly in the viewport. Press a flat face or a profile and pull: up extrudes, down into a body cuts, and sideways movement sets the step size"); + /// Mouse gestures: a ring of tools on the right button. + mouse_gestures: crate::mouse_gesture::Config = Default::default(), PAGE_NAVIGATION; + /// The wheel zooms out when turned forward. + zoom_reverse: bool = false, PAGE_NAVIGATION => check("Reverse zoom direction"); + /// What an orbit turns around. + orbit_around: OrbitAround = OrbitAround::default(), PAGE_NAVIGATION; + /// The cursor preference as releases before the origin option saved it (`true` = the point + /// under the cursor). [`migrate`] folds it into `orbit_around` when saved preferences are + /// read, so an existing choice survives the upgrade; this version only writes `false`. + orbit_cursor: bool = false, PAGE_NAVIGATION; + /// Whether a connected 3D mouse moves the view. + space_mouse_enabled: bool = true, PAGE_NAVIGATION => check("Navigate with the 3D mouse"); + /// Whether a picture of the connected 3D mouse, moving as it does, sits in the 3D view's lower + /// left corner. Off by default. + space_mouse_in_view: bool = false, PAGE_NAVIGATION => check_id("ui.3d_mouse_show_in_view"); + /// Speed multiplier for 3D mouse navigation. + space_mouse_speed: f32 = 1.0, PAGE_NAVIGATION; + /// Per physical axis of the cap (push X, Y, Z, then tilt X, Y, Z), whether it moves the view + /// the other way. + space_mouse_reverse: [bool; 6] = [false; 6], PAGE_NAVIGATION; + /// Per physical axis of the cap, a multiplier on top of `space_mouse_speed`; 0 switches it off. + space_mouse_axis_speed: [f32; 6] = [1.0; 6], PAGE_NAVIGATION; + /// Per physical axis of the cap, which of its motions drives it (`space_mouse::reassigned`), + /// applied after calibration; each motion drives exactly one axis. + space_mouse_axis_source: [usize; 6] = crate::space_mouse::SAME_AXES, PAGE_NAVIGATION; + /// Which program reads the 3D mouse when spacenavd and the device itself are both there (Linux). + space_mouse_driver: SpaceMouseDriver = SpaceMouseDriver::default(), PAGE_NAVIGATION; + /// Where the 3D mouse picture sits in the 3D view, when it is shown there (`space_mouse_in_view`). + space_mouse_ghost_position: SpaceMouseGhost = SpaceMouseGhost::default(), PAGE_NAVIGATION; + /// The user turned the calibration offer off for good ("Never show again"). Unlike closing the + /// card, which only records that device, this stops every offer, for every device: it is one flag, + /// not kept per device key. Like the settings beside it, the dialog's Restore Defaults puts it back + /// (the 3D mouse section's own restore leaves it). + space_mouse_offer_never: bool = false, PAGE_NAVIGATION; + /// Per 3D mouse (`space_mouse::Input::device`), the calibration that puts its axes on + /// 3Dconnexion's. A device without one is read as it reports. Page resets keep calibrations. + #[serde(deserialize_with = "calibrations_that_read")] + space_mouse_calibrations: std::collections::BTreeMap = Default::default(); + /// Per 3D mouse, what each of its buttons does, by number from 1, once the user has changed + /// any of them; until then a measured device has its printed keys' jobs + /// (`space_mouse::default_button_jobs`). Kept, like calibrations, when settings are reset. + #[serde(deserialize_with = "button_jobs_that_read")] + space_mouse_buttons: std::collections::BTreeMap> = Default::default(); + /// The 3D mice (`space_mouse::Input::device`) whose calibration has been offered and dismissed, so + /// the offer (`space_mouse_offer`) is made once per device. A saved entry that is not text is dropped. + /// Kept when settings are reset, like the calibrations and button mappings it goes with: resetting + /// the page would otherwise bring the offer back for every device. + #[serde(deserialize_with = "devices_that_read")] + space_mouse_offered: std::collections::BTreeSet = Default::default(); + /// A device's own app on this computer moves the view (the navigation bridge, docs/3d-mouse.md): + /// the desktop app connects to it on `nav_bridge_port`. Off unless asked for, so the app + /// doesn't connect to whatever else listens on that port. + nav_bridge_enabled: bool = false, PAGE_NAVIGATION; + /// The loopback port the device app listens on (0: none). + nav_bridge_port: u16 = 8765, PAGE_NAVIGATION; + /// Anti-aliasing samples (applies on restart). + msaa: u32 = 4, PAGE_GRAPHICS; + /// Linux: the window system the app opens with at its next start (#3083): `auto` (XWayland + /// whenever there is an X display, native Wayland on niri), `wayland` or `x11`. + window_system: String = "auto".into(), PAGE_GRAPHICS; + /// Exact graphics adapter name; empty selects automatically on the next start. + graphics_adapter: String = String::new(), PAGE_GRAPHICS; + /// Soft contact shading in the GPU viewport; optional and applied immediately. + ambient_occlusion: bool = false, PAGE_GRAPHICS; + /// Optional schematic markings on threaded cylindrical walls; off for new and older preferences. + cosmetic_threads: bool = false, PAGE_GRAPHICS; + /// The grid turns to the upright origin plane facing a side view (#1470). Off by default: the + /// grid stays on the ground plane (XY) whatever the view. + grid_follows_view: bool = false => check("Grid follows the view", "Side views show the grid on the upright plane facing them instead of the ground"); + /// Draw reference geometry such as inactive sketches and datum planes through shaded bodies. + /// Off by default to preserve the depth-tested viewport behaviour. + reference_geometry_through_bodies: bool = false, PAGE_GRAPHICS => check_id("settings.reference_geometry_through_bodies"); + /// A small dot at every vertex wherever edges are drawn (#7834). Off by default: the viewport + /// draws edges only, as it always has. + vertex_markers: bool = false => check("Vertex markers", "Show a small dot at every vertex wherever edges are drawn"); + /// Restore the previous platform-specific fixed Render preview geometry budget. + render_previous_geometry_budget: bool = false, PAGE_GRAPHICS => check_id("prefs.render_previous_geometry_budget"); + /// Open Result once after a successful GUI Start; false preserves the selected view. + render_open_result_on_start: bool = true, PAGE_GRAPHICS => check_id("prefs.render_open_result_on_start"); + /// CPU snapshot boundaries; false restores powers-of-two feedback without changing the sample target. + render_cpu_progressive_every_pass: bool = true, PAGE_GRAPHICS => check_id("prefs.render_cpu_progressive_every_pass"); + /// Interactive sampling policy; false restores its old16SPP/seed0 envelope. + render_cpu_interactive_explicit_sampling: bool = true, PAGE_GRAPHICS => check_id("prefs.render_cpu_interactive_explicit_sampling"); + /// How finely the viewport tessellates curved faces and edges: `coarse`, `normal`, `fine` or + /// `ultra` (#1287). Only the display plan the viewport draws; never the design or exports. + display_quality: String = "normal".into(), PAGE_GRAPHICS; + /// Supersampling (#1288): the view drawn at this many times its pixels each way and filtered + /// down (1, 1.5 or 2; 1 is off). + supersampling: f32 = 1.0, PAGE_GRAPHICS; + /// Supersample only while the view holds still (full speed while orbiting). + supersampling_adaptive: bool = true, PAGE_GRAPHICS => check_tr("ui.supersampling_adaptive"); + /// Show the frame rate in the view's corner (the view then redraws every frame). + show_frame_rate: bool = false, PAGE_GRAPHICS => check_id("ui.frame_rate"); + /// With the frame rate: a frame-time graph, a histogram and what the GPU drew (#2548). + frame_rate_details: bool = false, PAGE_GRAPHICS; + /// Draw a wider rim under finished sketch curves to improve contrast on shaded faces. + sketch_halo: bool = false, PAGE_GRAPHICS => check("Halo under sketch curves"); + /// Show the view's pitch, yaw and roll and its projection under the orientation gizmo (#6032). + /// Off by default; View ▸ View angles and `view.angle_readout` turn it on. + show_view_angles: bool = false, PAGE_GRAPHICS; + /// Show world X/Y/Z component dimensions beside the total distance in Measure. + measure_axis_distances: bool = true, PAGE_GRAPHICS => check_id("settings.measure_axis_distances"); + /// Decimals shown for lengths and angles. + length_decimals: u8 = 2, PAGE_DESIGN; + angle_decimals: u8 = 1, PAGE_DESIGN; + /// Up/Down and the wheel over a focused value field step its plain number (`value_step`, + /// #2320). Off by default: the keys move the text cursor and the wheel scrolls, as before. + step_values: bool = false, PAGE_DESIGN => check_id("ui.step_values"); + /// A design coming back to its tab reads again the linked designs whose files changed since + /// it last read them. Off: they wait for Update Links, as before. + update_changed_links: bool = true, PAGE_DESIGN => check_id("settings.update_changed_links"); + /// A double-click on a component, in the browser or on its face in the view, opens a linked + /// one's design with the assembly around it (`edit_in_place`) and activates any other. Off: + /// a double-click in the browser activates every component and one in the view does nothing, + /// as before. + double_click_components: bool = true, PAGE_DESIGN => check_id("settings.double_click_components"); + /// Reopen the saved designs that were open when the app was last closed (#5542). + reopen_designs: bool = true, PAGE_GENERAL; + /// Those designs' files, in tab order, as the last quit left them. + open_designs: Vec = Vec::new(), PAGE_GENERAL; + /// The largest STEP or import file opened, in MB (#4086): from the default (512) up to 16 GB. + /// `--max-file-size` overrides it for one run. The browser keeps the default. + max_step_file_mb: u64 = DEFAULT_STEP_MB, PAGE_GENERAL; + /// The largest design file opened or saved, in MB (#4086): from the default (256) up to 16 GB. + max_design_file_mb: u64 = DEFAULT_DESIGN_MB, PAGE_GENERAL; + /// Explicit assembly Move uses joint handles; off keeps the previous Move panel. + assembly_move_handles: bool = true, PAGE_DESIGN => check_id("joint_move.use_handles"); + /// Degrees per step near the assembly Move ring. + joint_rotation_coarse: f64 = 10.0, PAGE_DESIGN; + /// Degrees per step after pulling the cursor outside the precision guide. + joint_rotation_fine: f64 = 0.1, PAGE_DESIGN; + /// `dark`, `light` or `system` (follow the operating system), or a theme file's id: a + /// built-in one (`gruvbox-dark`, …) or one of `custom_themes` (#2255). + theme: String = "dark".into(), PAGE_INTERFACE; + /// The 3D view's colours: the theme's own, or the Light or Dark theme's whatever the window + /// uses (#4146). + viewport_theme: crate::theme::ViewportTheme = crate::theme::ViewportTheme::Theme, PAGE_INTERFACE; + /// The 3D view's background, one colour for the whole application (#7688), or `None` (the + /// default) for the theme's gradient. + viewport_background: Option<[u8; 3]> = None, PAGE_INTERFACE; + /// The application bar's logo in the theme's accent instead of the theme's logo colours. + logo_accent: bool = false, PAGE_INTERFACE; + /// Imported theme files (`theme_files`), kept here so they also work in the browser. + custom_themes: Vec = Vec::new(); + /// Desktop: a `solidcraft-theme/1` file another tool writes, followed as the theme and + /// reloaded when it changes (#7573). Empty (the default): no file is followed. + theme_follow: String = String::new(), PAGE_INTERFACE; + /// Interface language (a registered locale ID). + language: String = "en".into(), 0; + /// Shared workspace composition; system windows and popups retain their purpose. + layout: crate::shell::LayoutMode = Default::default(), PAGE_INTERFACE; + /// Ordered view controls and their appearance. + #[serde(default)] + navigation_bar: crate::navigation_bar::NavigationBar = Default::default(), PAGE_INTERFACE; + /// Show command names beneath ribbon icons, independently of workspace layout. + ribbon_labels: bool = true, PAGE_INTERFACE; + /// Keep the SKETCH tab in the ribbon, right after MODEL, while no sketch is open; its drawing + /// tools then start a sketch first (#7904). + sketch_tab_always: bool = false, PAGE_INTERFACE => check_id("prefs.sketch_tab_always"); + /// Where a dialog's OK and Cancel sit: under its inputs (the default) or in its title row (#6708). + dialog_buttons: crate::ui_kit::DialogButtons = Default::default(), PAGE_INTERFACE; + /// Where notices and offers stack: the view's bottom-right corner (the default) or the bottom + /// centre, as before #7893. + toast_place: crate::viewport::ToastPlace = Default::default(), PAGE_INTERFACE; + /// Toolbar tabs hidden by the person. An empty list keeps every existing tab visible. + hidden_toolbar_tabs: Vec = Vec::new(), PAGE_INTERFACE; + /// Interface scale (1 = 100 %). + ui_scale: f32 = 1.0, PAGE_INTERFACE, accept(0.5..=2.5); + /// Interface font: an installed font family (or a font file), or empty for the built-in one + /// (#1290). Menus, dialogs and labels use it; glyphs it lacks fall back as before. + ui_font: String = String::new(), PAGE_INTERFACE; + /// While a dialog or a sketch is open, OK and Cancel in the view's top right corner, with the + /// axis view moved down below them (#6709). Off by default. + view_confirm_corner: bool = false, PAGE_INTERFACE => check_id("prefs.view_confirm_corner"); + /// A thin bar along the window's bottom edge: what is being edited, the open sketch's state + /// and the design's units (#7243). Off by default. + status_bar: bool = false, PAGE_INTERFACE => check_id("prefs.status_bar"); + /// Put the feature history to the left of the browser instead of below the viewport. + timeline_left: bool = false, PAGE_INTERFACE; + /// Measured outer width; the contents react to this width without a names mode. + timeline_left_width: f32 = 130.0, PAGE_INTERFACE; + /// Share the browser column, vertically, instead of a separate left column. + timeline_under_browser: bool = false, PAGE_INTERFACE; + /// Compact history: the browser lists each component's features in history order with the + /// marker, and neither timeline is shown. + history_in_browser: bool = false, PAGE_INTERFACE; + /// Fold the shared-column history to its header. + timeline_collapsed: bool = false, PAGE_INTERFACE; + /// The browser's share of the column's height when History sits under it, which the user + /// drags at the seam between the two cards (#7371). + browser_share: f32 = DEFAULT_BROWSER_SHARE, PAGE_INTERFACE; + /// Whether the browser beside the vertical history is collapsed to its rail. + timeline_left_browser_collapsed: bool = false, PAGE_INTERFACE; + /// Whether the History at the left lists a sketch under the feature built from it. + history_sketches: HistorySketches = HistorySketches::default(), PAGE_INTERFACE; + /// A Play History button in the History controls, between Previous and Next (#3688). Off + /// gives the four controls History had before; right-clicking the controls toggles it too. + history_play_button: bool = true, PAGE_INTERFACE => check_id("prefs.history_play_button"); + /// The vertical history (left, or under the browser) starts with the active component's Bodies + /// folder and the Origin, as the browser shows them (#6490). The bottom strip is unchanged. + timeline_origin_bodies: bool = false, PAGE_INTERFACE; + /// Width of the browser sidebar, which + /// the user drags wider or narrower at its right edge. + browser_width: f32 = DEFAULT_BROWSER_WIDTH, PAGE_INTERFACE; + /// Render shell preference, independent of the document and Design history. + render_shots_strip: bool = true; + render_inspector_side: String = "right".into(); + render_inspector_width: f32 = 305.0; + render_browser_side: String = "left".into(); + render_browser_width: f32 = 266.0; + /// Resource identities and history belong to the user, never the design. + render_library_favorites: std::collections::BTreeSet<(String, String)> = Default::default(); + render_library_recent: std::collections::VecDeque<(String, String)> = Default::default(); + /// Draw the parts browser on a translucent card over the 3D view instead of a column of its + /// own, so the workspace keeps the whole window width. + browser_float: bool = false, PAGE_INTERFACE; + /// The browser card folded to its header with the chevron in that header, kept from one run + /// to the next like the toolbar's pins (#8692). + browser_collapsed: bool = false, PAGE_INTERFACE; + /// Whether the browser card is always shown or kept out of sight until the pointer comes to + /// it, as the navigation bar's "Hide until hovered" does (#8692). + browser_show: crate::browser::BrowserShow = Default::default(), PAGE_INTERFACE; + /// Where command dialogs open: at the view's edge, or in the left column in place of the + /// browser and the History there (#6707). + dialog_place: crate::dialog_column::DialogPlace = Default::default(), PAGE_INTERFACE; + /// The names the browser, dialogs and lists show for the origin planes (#6491). + origin_plane_names: OriginPlaneNames = OriginPlaneNames::default(), PAGE_INTERFACE; + /// When components' bodies sit in a Bodies folder in the browser (#4217). + browser_bodies_folders: BodiesFolders = BodiesFolders::Several, PAGE_INTERFACE; + /// The wheel zooms toward the point under the cursor (else toward the view's centre). + zoom_to_cursor: bool = true, PAGE_NAVIGATION => check("Zoom to the cursor", "The wheel zooms toward the point under the cursor (off: toward the view's centre)"); + /// Speed multiplier for wheel zoom, independent of the 3D mouse. + wheel_zoom_speed: f32 = 1.0, PAGE_NAVIGATION, accept(0.25..=4.0) => slider("ui.wheel_zoom_speed", 0.25..=4.0, 0.05, |v| format!("{v:.2}×"), "prefs:wheel_zoom_speed"); + /// Spread discrete wheel input across frames (off: apply each event immediately). + smooth_wheel_zoom: bool = true, PAGE_NAVIGATION => check("Smooth wheel zoom", "Turn off to apply each wheel event immediately, without a smoothing tail"); + /// Two-finger trackpad scroll pans (off: it zooms like the wheel); pinch always zooms. + trackpad_pan: bool = true, PAGE_NAVIGATION; + /// Hold this modifier alone to zoom with vertical wheel or two-finger scroll. + trackpad_zoom_modifier: TrackpadZoomModifier = TrackpadZoomModifier::default(), PAGE_NAVIGATION; + /// Horizontal trackpad and thumb-wheel scrolling pans the view the other way (#2007). + pan_reverse_x: bool = false, PAGE_NAVIGATION => check("Reverse horizontal pan direction", "Horizontal two-finger scrolling and the thumb wheel pan the other way"); + /// Vertical trackpad scrolling pans the view the other way (#5240). + pan_reverse_y: bool = false, PAGE_NAVIGATION => check("Reverse vertical pan direction", "Vertical two-finger scrolling pans the other way"); + /// Shift with two-finger trackpad scrolling orbits the view the other way, both ways at once, + /// as natural scrolling turns it (#8410). + orbit_reverse: bool = false, PAGE_NAVIGATION => check("Reverse trackpad orbit direction", "Shift with two-finger scrolling orbits the other way"); + /// View changes (axis view, Look At, Home) animate; `look_at_speed` scales how fast. + look_at_anim: bool = true, PAGE_NAVIGATION => check("Animate view changes", "Axis view, Look At, Home and Fit"); + look_at_speed: f32 = 1.0, PAGE_NAVIGATION, accept(0.25..=4.0) => enabled_slider(look_at_anim, "Animation speed", 0.5..=3.0, 0.25, |v| format!("{v:.2}×")); + /// Default modelling orientation: `z` (Z up) or `y` (Y up) (#3). + up_axis: String = "z".into(), PAGE_DESIGN; + /// After a STEP or IGES file opens, offer to stand a Y-up part up (`stand_up`). + offer_stand_up: bool = true, PAGE_DESIGN => check("Offer to stand up Y-up files", "After a STEP or IGES file opens with Z up, offer a quarter turn about X"); + /// How the offer is made for a file whose header names no program known to save Y up: a note + /// over the view (the default), the dialog, or nothing (#7717). + stand_up_unknown: StandUpUnknown = StandUpUnknown::default(), PAGE_DESIGN; + /// Extrude: with a profile picked, a face, vertex or parallel plane picked off its plane + /// switches the extent to To Object (off: picks only add profiles, as before). + extrude_auto_to_object: bool = false, PAGE_DESIGN => check("Extrude to a picked target", "In Extrude, with a profile picked, picking a face, vertex or parallel plane off its plane switches the extent to To Object"); + /// Feature windows choose Join, New Body or Cut from what their material touches (`op_auto`, + /// #6901). Off: they keep the operation they open with (Extrude its own Join or Cut), as before. + auto_operation: bool = true, PAGE_DESIGN => check_id("prefs.auto_operation"); + /// Placing a Single hole snaps to the middle of the face and the centres of its round edges + /// (`hole_place`). Off by default: a hole goes where it is clicked. + hole_snaps: bool = false, PAGE_DESIGN => check("Snap to face and edge centres"); + /// A placed Single hole has a handle that drags it, and a pick elsewhere on a face that has a + /// hole moves the hole there (`hole_place`). Off by default: a second pick on its face takes + /// the hole out, and a hole is moved by taking it out and picking again. + hole_moves: bool = false, PAGE_DESIGN => check("Move holes by clicking or dragging"); + /// The browser's Origin folder starts hidden in designs that don't keep its eye themselves. + hide_origin: bool = false, PAGE_DESIGN => check_tr("ui.hide_origin_by_default"); + /// Handles on the preview of a feature placed on a face (Rest, Boss, Snap Fit): a marker that + /// drags it across the model and a ring that turns it. Off by default: the feature is then placed + /// by its click only, as before, and its Position input takes faces only. + placement_handles: bool = false, PAGE_DESIGN => check("Placement handles", "Handles on the preview of a Rest, Boss or Snap Fit: drag the marker to move it across the model, turn it by its ring"); + /// The files a design names (linked designs, font files) may be on any network location, for + /// organisations that keep their designs on file servers. Off (the default): only on the + /// servers in `network_hosts`, or one the user allows when asked (`network_prompt`). + network_locations: bool = false, PAGE_DESIGN => check_tr("prefs.network_locations"); + /// The servers the files a design names may be on ("Always allow this server"). + network_hosts: Vec = Vec::new(), PAGE_DESIGN; + /// What a middle-button double-click in the view does: `home`, `fit` or `off`. + middle_double_click: String = "home".into(), PAGE_NAVIGATION; + /// Colour vision mode (#778): `off`, `protan`, `deutan` or `tritan`. + color_vision: crate::theme::ColorVision = crate::theme::ColorVision::Off, PAGE_INTERFACE; + /// Check for updates at start and once a day (docs/updates.md). + check_updates: bool = true, 0; + /// When the last update check ran, and the versions skipped or put off (`update::Memo`). + update: crate::update::Memo = crate::update::Memo::default(); + /// The variant last started in each split tool family (Rectangle, Circle, Arc, Slot, Polygon, Line, + /// Spline): the family's button and shortcut start it again (`sketch_families`). + sketch_variants: crate::sketch_families::Choices = crate::sketch_families::Choices::default(); + /// Personal Hole parameter combinations, shared by every design in this profile. + /// No page reset discards this user-authored library. + hole_presets: crate::hole_presets::Library = crate::hole_presets::Library::default(); + /// Save as mesh: the last format (`stl` or `3mf`). Older versions also kept a "send to slicer" + /// choice here (`save_mesh_send`, `save_mesh_slicer`); a settings file that still has them loads, + /// and they are ignored. + save_mesh_format: String = "stl".into(); + /// Hidden edges in the current-view DXF export (false: omit, true: dashed). + view_dxf_dashed: bool = false; + /// Model-space chord tolerance for current-view DXF curves, in millimetres. + view_dxf_tolerance: f64 = 0.01; + /// Send to Slicer: the last slicer used (an installed slicer's id or a program path). + send_slicer: String = String::new(); + /// Slicers that can load a file into the window that is already open do so (default on). + slicer_single_instance: bool = true, 0; + /// The line about sending again replacing the slicer's file has been shown. + slicer_resend_hint_seen: bool = false; + /// The user has agreed to Open with EasyPrint uploading a model to Printables' servers. + easyprint_consent: bool = false; + /// Save as mesh: the last quality (`standard`, `fine` or `finest`, #4747). + save_mesh_quality: String = "standard".into(); + /// The programs the user added to the slicer list, newest first. + custom_slicers: Vec = Vec::new(); + /// AI features (docs/agent-chat.md): the master switch. Off: no AI button, shortcut, menu + /// entry or panel, and nothing is looked for or started. + ai_features: bool = true, PAGE_AI; + /// The Assistant button in the application bar (the shortcut and View menu entry stay). + ai_toolbar_button: bool = true, PAGE_AI; + /// An agent's slow commands over the control channel (MCP) compute off the window thread, + /// so the window stays live while they run (#1989, [`crate::control_job`]). Off: they run on + /// the window thread, and the window waits for each, as before (the default). + agent_off_thread: bool = false, PAGE_AI; + /// Let AI agents connect: the localhost control channel (MCP) opens on the default port at + /// start-up, unless `--control`/`SOLIDCRAFT_CONTROL_PORT` name one. Read at start-up. + agent_control: bool = true, PAGE_AI; + /// Add SolidCraft's MCP server to the AI apps installed on this computer at start-up + /// ([`crate::ai_connect`]); off takes the entries out again. + connect_ai_apps: bool = true, PAGE_AI; + /// Agents the user added (the installed ones are found by themselves). API keys are never + /// here: they live in the system keychain. + agents: Vec = Vec::new(); + /// The agent a new conversation starts with (an agent's id; empty: the first one available). + agent_default: String = String::new(); + /// The agent the chat last started (an agent's id; empty: none yet). + agent_last: String = String::new(); + /// When SolidCraft starts: connect the agent started last (`agent_last`, else the one a new + /// conversation starts with), and open the panel (#7009). Off by default: an agent starts + /// only when a message is sent or Connect is pressed, and the panel opens when asked for. + agent_connect_at_start: bool = false, PAGE_AI; + agent_chat_open_at_start: bool = false, PAGE_AI; + /// How much the agent may do without asking (`ask`, `edits`, `all`), and per agent. + ai_permissions: crate::agent_chat::agents::Mode = crate::agent_chat::agents::Mode::Edits, PAGE_AI; + agent_permissions: std::collections::BTreeMap = Default::default(), PAGE_AI; + /// The model last chosen in the chat, per agent: put back when the agent offers it again. + agent_models: std::collections::BTreeMap = Default::default(); + /// "Always allow" answers: per agent, the tools it may use without asking. + agent_always_allow: std::collections::BTreeMap> = Default::default(); + /// The side the panel docks on (`left` or `right`), its width, and whether it is folded to a strip. + agent_chat_side: String = "right".into(), PAGE_AI; + agent_chat_width: f32 = 380.0, PAGE_AI; + agent_chat_minimized: bool = false, PAGE_AI; + /// Whether the chat is in its own window instead of the side panel, and that window's place + /// and size as the system last reported them (`[x, y, width, height]`, points; `x` can be + /// negative or past the main screen when the window sits on another one). + agent_chat_popped: bool = false, PAGE_AI; + agent_chat_window: Option<[f32; 4]> = None, PAGE_AI; + /// Changes the agent may make for one message; 0 is no limit. + agent_chat_turn_limit: u32 = crate::agent_chat::gate::DEFAULT_TURN_LIMIT, PAGE_AI; + + // ---- Sketch / selection modifier bindings (classic defaults; alternate mapping is opt-in) ---- + /// Modifier that suppresses sketch auto-snap while drawing or dragging a sketch point. + /// Default: Alt/Option. Set to Ctrl/Cmd for the alternate mapping. + suppress_sketch_snap: ModifierCombo = ModifierCombo::CTRL_ALT, PAGE_SKETCH; + /// Temporary horizontal/vertical guides from hovered centres and edge midpoints. + sketch_tracking_guides: bool = true, PAGE_SKETCH; + /// Open Project's options before picking; off restores its previous direct-pick workflow. + project_options_dialog: bool = true, PAGE_SKETCH; + /// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does). + manipulator_free_alt: bool = true, PAGE_SKETCH; + /// A sketch's icon in History and the browser takes the colour of its solve state, and its + /// tooltip names the state (#7245). Off: every sketch has the same icon, as before. + sketch_state_icons: bool = true, PAGE_SKETCH => check_id("prefs.sketch_state_icons"); + /// A sketch tool's shortcut pressed again before the first point steps to the tool's next + /// creation mode (#2459). Off (the default): the key starts the tool again, as it always has. + shortcut_cycles_modes: bool = false, PAGE_SKETCH; + /// Where the view goes when a sketch ends (#7038). Keep (the default) leaves it as it is. + sketch_exit_view: SketchExitView = SketchExitView::default(), PAGE_SKETCH; + /// A shape drawn in a sketch gets all its dimensions at once: the typed values, and every + /// other size the shape has at its size as drawn (`sketch.draw.dimensioned` with `as_drawn`). + /// Shapes `solidcraft_engine::dimension_roles` doesn't list are drawn as before. + sketch_auto_dimensions: bool = false, PAGE_SKETCH => check( + "Dimension new shapes", + "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out." + ); + /// With `sketch_auto_dimensions`: new shapes are also placed from the sketch origin until they + /// are fully constrained (`sketch.draw.dimensioned` with `locate`). A shape already anchored to + /// the origin or to placed geometry gets nothing more. + sketch_auto_locate: bool = false, PAGE_SKETCH => check( + "Also place them from the origin (fully constrained)", + "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none." + ); + /// A centre-point arc runs the way the cursor goes round its centre from the start (#6645). + /// Off: it always runs counter-clockwise from the start, as it did before. + center_arc_follows_cursor: bool = true, PAGE_SKETCH; + /// When true: Shift+click adds without removing; Primary toggles. + /// When false (default): Shift and Primary both toggle. + selection_shift_add_only: bool = false, PAGE_SKETCH; + /// Prefer movable sketch points on exact selection ties; off keeps point insertion order. + prefer_free_sketch_points: bool = true, PAGE_SKETCH; + /// While the open sketch's constraints conflict, the curves and points a failing constraint + /// holds, and its glyph or dimension, are drawn in `sketch_conflict` (#7244). Off: only the + /// glyphs and dimensions are red, in `error`, as before. + sketch_conflict_colour: bool = true, PAGE_SKETCH => check_id("prefs.sketch_conflict_colour"); + /// Drive Joints shows the moved parts' old place as a ghost (its Show ghost box, #5905). + drive_joints_ghost: bool = true, PAGE_DESIGN; + /// Plugin ids turned off (Preferences › Plugins). An installed plugin whose id is absent is on. + disabled_plugins: std::collections::BTreeSet = std::collections::BTreeSet::new(), PAGE_PLUGINS; +} + +/// What a middle-button double-click in the view does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MiddleDoubleClick { + /// Go Home (the iso view, framing what is shown). + Home, + /// Frame what is shown, keeping the orientation. + Fit, + Off, +} + +impl MiddleDoubleClick { + pub const ALL: [(MiddleDoubleClick, &'static str, &'static str); 3] = + [(MiddleDoubleClick::Home, "home", "Home"), (MiddleDoubleClick::Fit, "fit", "Fit"), (MiddleDoubleClick::Off, "off", "Off")]; + + /// The preference's setting (Home for an unknown one). + pub fn of(app: &SolveApp) -> MiddleDoubleClick { + Self::parse(&app.preferences.middle_double_click).unwrap_or(MiddleDoubleClick::Home) + } + + pub fn parse(id: &str) -> Option { + Self::ALL.iter().find(|(_, i, _)| *i == id).map(|(m, _, _)| *m) + } + + pub fn label(self) -> &'static str { + Self::ALL.iter().find(|(m, _, _)| *m == self).map_or("Home", |(_, _, l)| l) + } +} + +/// The preferences window. +#[derive(Default)] +pub struct PrefsWindow { + navbar: navbar::State, + navbar_scroll: bool, + pub open: bool, + /// The page shown (index into [`PAGES`]). + pub section: usize, + /// Everything as it was when the dialog opened (or at the last Apply), for Cancel. + snapshot: Option, + /// The up axis preference the view follows now (applied when it changes, and at startup). + applied_up: Option, + /// The search text of the interface font list. + font_filter: String, + /// Search text on the Plugins page. + pub(crate) plugin_query: String, + /// The followed theme file's state (#7573): its last good theme and why a read failed. + pub(crate) follow: crate::theme_files::Follow, + /// Filters every page. Empty leaves the selected page as it is. + pub filter: String, + /// The page on screen when the current search started. Clearing the field returns there. + search_from: Option, + /// Set when a result is chosen, so the page draw does not put the previous tab back. + land_on: Option, + /// The row to scroll to after a result is chosen. + reveal: Option, + /// Where the theme Import tile was drawn last frame: a file dropped there is a theme (#8226). + import_tile: Option, +} + +/// Following a theme file needs the file system: the desktop app only (#7573). +const FOLLOW_AVAILABLE: bool = cfg!(not(target_arch = "wasm32")); + +/// Follow `path` as the theme for this run (the `--theme-file` launch flag), without saving it. +pub fn follow_theme_file_for_run(app: &mut SolveApp, path: &str) -> Result<(), String> { + if !FOLLOW_AVAILABLE { + return Err(FOLLOW_UNAVAILABLE.into()); + } + let path = crate::theme_files::follow_path(path)?; + app.prefs_window.follow.launch = (!path.is_empty()).then_some(path); + Ok(()) +} + +const FOLLOW_UNAVAILABLE: &str = "`theme_follow` is not available in the browser: it follows a file on this computer; import the theme instead"; + +/// Stop following a theme file: the preference and this run's launch flag. The chosen theme +/// takes over again, with its own dark or light. +fn stop_following(app: &mut SolveApp) { + let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty(); + app.preferences.theme_follow.clear(); + app.prefs_window.follow.launch = None; + if following { + let theme = app.preferences.theme.clone(); + select_theme(app, &theme); + } +} + +/// Look at the followed theme file (#7573): every second while the app runs and whenever the +/// window gains the focus. A new failure is reported once in the status bar; a recovery too. +fn follow_theme_file(app: &mut SolveApp, ctx: &egui::Context) { + if !FOLLOW_AVAILABLE { + return; + } + let (now, focused) = ctx.input(|i| (i.time, i.focused)); + let follow = &mut app.prefs_window.follow; + let gained_focus = focused && !follow.focused; + follow.focused = focused; + let path = follow.path(&app.preferences.theme_follow).to_string(); + let had_error = follow.error().is_some(); + match follow.poll(&path, now, gained_focus) { + crate::theme_files::FollowChange::None => {} + crate::theme_files::FollowChange::Loaded(name) => { + if had_error { + app.set_status(format!("Theme file loaded again: {name}"), false); + } + } + crate::theme_files::FollowChange::Failed(e) => app.set_status(format!("Theme file not applied: {e} (the last good theme stays on)"), true), + } + if !path.is_empty() { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(crate::theme_files::FOLLOW_INTERVAL)); + } +} + +/// `ui.prefs` `theme_follow`: a path follows that file (read at once, so the reply has any +/// error), `""` stops following. +fn set_theme_follow(app: &mut SolveApp, value: &serde_json::Value, available: bool) -> Result<(), String> { + if !available { + return Err(FOLLOW_UNAVAILABLE.into()); + } + let path = value.as_str().ok_or("`theme_follow` must be a theme file's path, or \"\" to stop following")?; + let path = crate::theme_files::follow_path(path)?; + if path.is_empty() { + stop_following(app); + return Ok(()); + } + app.prefs_window.follow.launch = None; + app.preferences.theme_follow = path.clone(); + // Read now, so the reply has any error; the next frame's look then follows on as usual. + let _ = app.prefs_window.follow.poll(&path, f64::NEG_INFINITY, true); + Ok(()) +} + +/// Open the dialog at a page. +pub fn open_at(app: &mut SolveApp, page: usize) { + app.prefs_window.open = true; + app.prefs_window.section = page.min(PAGES.len() - 1); +} + +/// Every setting the dialog changes, for Cancel and Restore Defaults. +#[derive(Clone)] +struct Snapshot { + prefs: Prefs, + dark: bool, + layout: crate::shell::LayoutMode, + grid: bool, + navigation_bar: bool, + tool_cursor: bool, + shadow: bool, + perspective: bool, + style: u8, + pick_bodies: bool, + agent: crate::agent_cursor::Settings, + autosave: f64, + auto_project: bool, + keys: std::collections::BTreeMap>, +} + +impl Snapshot { + fn take(app: &SolveApp) -> Snapshot { + Snapshot { + prefs: app.preferences.clone(), + dark: app.ui.dark, + layout: app.ui.layout, + grid: app.ui.show_grid, + navigation_bar: app.ui.show_navigation_bar, + tool_cursor: app.ui.tool_cursor, + shadow: app.ui.ground_shadow, + perspective: app.ui.perspective, + style: app.ui.visual_style, + pick_bodies: app.ui.pick_bodies, + agent: app.ui.agent_cursor, + autosave: app.autosave_minutes, + auto_project: app.session.auto_project, + keys: app.keymap.custom.clone(), + } + } + fn restore(self, app: &mut SolveApp) { + let graphics = (app.preferences.msaa, app.preferences.window_system.clone(), app.preferences.graphics_adapter.clone()); + let units_changed = app.preferences.default_units != self.prefs.default_units; + // Update bookkeeping isn't a setting: a check that finished while the dialog was open stays. + let update = std::mem::take(&mut app.preferences.update); + app.preferences = self.prefs; + app.preferences.update = update; + if units_changed { + default_units_changed(app); + } + app.ui.dark = self.dark; + app.ui.layout = self.layout; + app.ui.show_grid = self.grid; + app.ui.show_navigation_bar = self.navigation_bar; + app.ui.tool_cursor = self.tool_cursor; + app.ui.ground_shadow = self.shadow; + app.ui.perspective = self.perspective; + app.ui.visual_style = self.style; + app.ui.pick_bodies = self.pick_bodies; + app.ui.agent_cursor = self.agent; + app.autosave_minutes = self.autosave; + set_autosave(app); + app.session.auto_project = self.auto_project; + app.keymap.custom = self.keys; + if (app.preferences.msaa, app.preferences.window_system.clone(), app.preferences.graphics_adapter.clone()) != graphics { + save_graphics(app); + } + } + + /// Whether everything is as in the snapshot: nothing Cancel would put back. Destructured, so + /// a setting added to the snapshot can't be left out of the comparison. + fn matches(&self, app: &SolveApp) -> bool { + let Snapshot { + prefs, + dark, + layout, + grid, + navigation_bar, + tool_cursor, + shadow, + perspective, + style, + pick_bodies, + agent, + autosave, + auto_project, + keys, + } = self; + *prefs == app.preferences + && *dark == app.ui.dark + && *layout == app.ui.layout + && *grid == app.ui.show_grid + && *navigation_bar == app.ui.show_navigation_bar + && *tool_cursor == app.ui.tool_cursor + && *shadow == app.ui.ground_shadow + && *perspective == app.ui.perspective + && *style == app.ui.visual_style + && *pick_bodies == app.ui.pick_bodies + && *agent == app.ui.agent_cursor + && *autosave == app.autosave_minutes + && *auto_project == app.session.auto_project + && *keys == app.keymap.custom + } +} + +/// Whether Apply has anything to do (#8561): something changed since the dialog opened or since +/// the last Apply. False while the dialog is closed. +fn apply_pending(app: &mut SolveApp) -> bool { + let Some(snapshot) = app.prefs_window.snapshot.as_mut() else { + return false; + }; + // Update bookkeeping isn't a setting and Cancel keeps it (`restore`), so it isn't a change. + snapshot.prefs.update.clone_from(&app.preferences.update); + app.prefs_window.snapshot.as_ref().is_some_and(|s| !s.matches(app)) +} + +/// The colour theme (#2255): Dark, Light, System, the built-in theme files and the imported +/// ones, with Import…, Export… (the theme on now as a complete file, to start a new one from) +/// and Remove (an imported theme). Like the other preferences, a choice applies at once. +fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut choices = theme_choices(app); + // While a file is followed (#7573) it is the theme, so no tile shows as chosen. + let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty(); + choices.sort_by_key(|(id, _)| match id.as_str() { + "light" => 0, + "dark" => 1, + "system" => 2, + _ => 3, + }); + let mut tile_action: Option<(&str, String)> = None; + let mut action_theme: Option = None; + let mut chosen: Option = None; + let mut action: Option<&str> = None; + let mut import_tile = None; + ui_kit::theme_rail( + ui, + |ui| { + for (id, label) in &choices { + let palette = match id.as_str() { + "light" | "system" => Tokens::light(), + "dark" => Tokens::dark(), + _ => crate::theme_files::find(id, &app.preferences.custom_themes).map(crate::theme_files::resolve).unwrap_or_else(Tokens::dark), + }; + let custom = app.preferences.custom_themes.iter().any(|t| t.id == *id); + let note = app.tr(if id == "system" { + "prefs.follows_os" + } else if custom { + "prefs.imported_file" + } else { + "prefs.built_in" + }); + let response = ui_kit::option_card( + ui, + label, + Some(note), + !following && app.preferences.theme == *id, + true, + ui_kit::PreferenceFigure::Theme { palette: palette.into(), system: id == "system" }, + ); + crate::scenario::publish_target(&format!("prefs:theme_tile:{id}"), response.rect); + crate::scenario::publish_target(&format!("prefs:theme:{id}"), response.rect); + if !following && app.preferences.theme == *id { + crate::scenario::publish_target("prefs:theme", response.rect); + } + if response.clicked() { + chosen = Some(id.clone()); + } + ui_kit::Menu::context(&response, |ui| { + ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| { + if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() { + tile_action = Some(("export", id.clone())); + ui.close(); + } + if custom { + let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete"); + remove.danger = true; + if remove.show(ui).clicked() { + tile_action = Some(("remove", id.clone())); + ui.close(); + } + } + }); + }); + } + }, + |ui| { + let tile = ui_kit::theme_import_tile(ui, app.tr_label("Import…"), app.tr("prefs.theme_file_or_paste")) + .on_hover_text(app.tr("prefs.theme_import_hint")); + import_tile = Some(tile.rect); + if tile.clicked() { + action = Some("import"); + } + // The keyboard's paste needs no menu; this is for touch screens and the browser's mouse users. + #[cfg(not(target_arch = "wasm32"))] + ui_kit::Menu::context(&tile, |ui| { + ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| { + if ui_kit::MenuItem::new("theme_paste", app.tr("prefs.theme_paste"), "paste").show(ui).clicked() { + action = Some("paste"); + ui.close(); + } + }); + }); + }, + ); + app.prefs_window.import_tile = import_tile; + if let Some((kind, id)) = tile_action { + action = Some(kind); + action_theme = Some(id); + } + if let Some(id) = chosen { + // Choosing a theme stops following a file (#7573). + stop_following(app); + select_theme(app, &id); + } + match action { + Some("import") => app.pick_open_for(&["json"], |app, path| { + let Some(path) = path else { return }; + // Through `vfs`, like every other import: in the web app a picked file is there. + let text = solidcraft_engine::io::vfs::read_to_string(&path, crate::theme_files::MAX_BYTES).map_err(|e| e.to_string()); + import_theme_text(app, text); + }), + #[cfg(not(target_arch = "wasm32"))] + Some("paste") => { + let text = arboard::Clipboard::new().and_then(|mut c| c.get_text()).unwrap_or_default(); + if looks_like_theme(&text) { + import_theme_text(app, Ok(text)); + } else { + app.set_status(app.tr("prefs.theme_paste_none").to_string(), true); + } + } + Some("export") => { + let system_dark = ui.ctx().system_theme().map_or(app.ui.dark, |theme| theme == egui::Theme::Dark); + let file = theme_file(app, action_theme.as_deref().unwrap_or(&app.preferences.theme), system_dark); + let name = file.get("name").and_then(serde_json::Value::as_str).unwrap_or("Theme").to_string(); + let text = serde_json::to_string_pretty(&file).unwrap_or_default(); + app.pick_save(&format!("{name}.json"), &["json"], move |app, path| { + // Through `vfs`, like every other save: the web app hands it out as a download. + if let Some(path) = path + && let Err(e) = solidcraft_engine::io::vfs::write(&path, text.as_bytes()) + { + app.set_status(format!("Theme export: {e}"), true); + } + }); + } + Some("remove") => { + let id = action_theme.unwrap_or_else(|| app.preferences.theme.clone()); + if let Err(e) = remove_theme(app, &id) { + app.set_status(e, true); + } + } + _ => {} + } +} + +/// Settings › Interface › Theme: a theme file to follow (#7573), chosen with the file picker, +/// and why its last read was not applied. The desktop app only. +fn follow_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let path = app.prefs_window.follow.path(&app.preferences.theme_follow).to_string(); + let launch = app.prefs_window.follow.launch.is_some(); + let error = app.prefs_window.follow.error().map(str::to_string); + let (mut choose, mut stop) = (false, false); + // The setting's name is longer than the label column: it leads the row's own line. + ui_kit::row(ui, "", |ui| { + // On a narrow page the buttons drop to a second line rather than widening the page. + let narrow = ui.available_width() < Tokens::get().form_card_width; + ui.horizontal_wrapped(|ui| { + ui_kit::text(ui, app.tr("prefs.theme_follow"), ui_kit::Text::Inline); + if narrow { + ui.end_row(); + } + let choose_button = ui_kit::button(ui, app.tr_label("Choose…"), ui_kit::Button::Small); + crate::scenario::publish_target("prefs:theme_follow", choose_button.rect); + choose = choose_button.clicked(); + let stop_button = ui_kit::button(ui, app.tr("prefs.theme_follow_stop"), ui_kit::Button::Enabled(!path.is_empty())); + stop = stop_button.clicked(); + let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()); + let shown = name.unwrap_or_else(|| app.tr("prefs.theme_follow_off").to_string()); + ui_kit::text(ui, &shown, ui_kit::Text::Inline).on_hover_text(&path); + }); + }); + if !path.is_empty() { + ui_kit::text(ui, app.tr(if launch { "prefs.theme_follow_launch" } else { "prefs.theme_follow_note" }), ui_kit::Text::Hint("theme_follow")); + } + if let Some(error) = error.filter(|_| !path.is_empty()) { + ui_kit::text(ui, &crate::i18n::format("prefs.theme_follow_error", &[("error", &error)]), ui_kit::Text::Error("theme_follow")); + } + if stop { + stop_following(app); + } + if choose { + app.pick_open_for(&["json"], |app, path| { + let Some(path) = path else { return }; + if let Err(e) = set_theme_follow(app, &serde_json::Value::String(path), FOLLOW_AVAILABLE) { + app.set_status(format!("Follow a theme file: {e}"), true); + } + }); + } +} + +/// The interface font (#1290): the built-in font first, then the installed families, with a +/// search box. The choice applies at once, like the other preferences. +fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let builtin = app.tr_label("Built-in").to_string(); + let current = if app.preferences.ui_font.trim().is_empty() { builtin.clone() } else { app.preferences.ui_font.clone() }; + let families = crate::sketch_text::families(ui.ctx()); + let mut values = vec![(String::new(), builtin.clone(), "prefs:font_builtin".to_string())]; + if let Some(families) = &families { + values.extend(families.iter().map(|family| (family.clone(), family.clone(), format!("prefs:font:{family}")))); + } + let options: Vec<_> = values.iter().map(|(value, label, handle)| ui_kit::SearchOption { value, label, handle: Some(handle) }).collect(); + let chosen = ui_kit::searchable_dropdown( + ui, + "pref_ui_font", + ¤t, + &mut app.prefs_window.font_filter, + &options, + None, + families.is_none().then(|| crate::i18n::tr_label("Listing the installed fonts…")), + ); + if let Some(rect) = crate::scenario::rect_of(&format!("dialog:widget:{}", crate::i18n::tr("prefs.font"))) { + crate::scenario::publish_handle("prefs:ui_font", rect.center()); + } + if let Some(name) = chosen { + if name.is_empty() || crate::fonts::ui_font(&name).is_some() { + app.preferences.ui_font = name; + } else { + app.set_status(format!("The font `{name}` could not be read"), true); + } + app.prefs_window.font_filter.clear(); + } +} + +/// Restore Defaults for one page. +fn defaults(app: &mut SolveApp, page: usize) { + let (msaa, window_system, adapter) = (app.preferences.msaa, app.preferences.window_system.clone(), app.preferences.graphics_adapter.clone()); + let units = app.preferences.default_units.clone(); + reset_preferences(&mut app.preferences, page); + if app.preferences.default_units != units { + default_units_changed(app); + } + match page { + 0 => { + app.autosave_minutes = 5.0; + set_autosave(app); + } + PAGE_INTERFACE => { + app.prefs_window.follow.launch = None; + app.ui.dark = true; + app.ui.layout = app.preferences.layout; + app.ui.show_navigation_bar = true; + } + PAGE_AI => app.ui.agent_cursor = Default::default(), + PAGE_NAVIGATION => app.ui.tool_cursor = false, + PAGE_DESIGN => {} + PAGE_SHORTCUTS => crate::keymap::reset(app, None), + PAGE_GRAPHICS => { + app.ui.visual_style = 0; + app.ui.show_grid = true; + app.ui.ground_shadow = true; + app.ui.perspective = false; + if app.preferences.msaa != msaa || app.preferences.window_system != window_system || app.preferences.graphics_adapter != adapter { + save_graphics(app); + } + } + PAGE_SKETCH => { + app.session.auto_project = true; + app.ui.pick_bodies = false; + } + _ => {} + } +} + +/// Settings that follow the preferences every frame: the theme when it follows the system, and +/// the interface scale. +pub fn apply(app: &mut SolveApp, ctx: &egui::Context) { + apply_network(&app.preferences); + apply_file_limits(&app.preferences); + // The viewport's display quality (an unknown saved value draws at Normal). + solidcraft_engine::doc::display_quality::set_current( + solidcraft_engine::doc::display_quality::DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default(), + ); + // The view's up axis follows the preference (set in the dialog, by ui.prefs or loaded). + if app.prefs_window.applied_up.as_deref() != Some(app.preferences.up_axis.as_str()) { + up_axis_changed(app); + } + if app.preferences.theme == "system" + && let Some(t) = ctx.system_theme() + { + app.ui.dark = t == egui::Theme::Dark; + } + // A theme file's palette, in place of its base's (dark or light); the visuals follow. A + // followed file (#7573) wins while it is followed and has read completely once. + follow_theme_file(app, ctx); + let file = app.prefs_window.follow.theme().or_else(|| crate::theme_files::find(&app.preferences.theme, &app.preferences.custom_themes)); + if let Some(f) = file { + app.ui.dark = f.base.is_dark(); + } + let custom = file.map(|f| crate::theme::Custom { dark: f.base.is_dark(), tokens: crate::theme_files::resolve(f) }); + if crate::theme::set_custom(custom) { + app.styled = false; + } + if crate::theme::set_logo_accent(app.preferences.logo_accent) { + app.styled = false; + } + // egui's end-of-frame shortcuts only change its context; the saved preference would + // overwrite that change next frame. Consume the desktop shortcuts into the preference. + if ctx.options(|o| o.zoom_with_keyboard) && !crate::keymap::capturing(app) { + use egui::gui_zoom::kb_shortcuts::{ZOOM_IN, ZOOM_IN_SECONDARY, ZOOM_OUT, ZOOM_RESET}; + if ctx.input_mut(|i| i.consume_shortcut(&ZOOM_RESET)) { + app.preferences.ui_scale = 1.0; + } else { + let zoom_in = ctx.input_mut(|i| i.consume_shortcut(&ZOOM_IN) || i.consume_shortcut(&ZOOM_IN_SECONDARY)); + let zoom_out = ctx.input_mut(|i| i.consume_shortcut(&ZOOM_OUT)); + if zoom_in != zoom_out { + app.preferences.ui_scale = (app.preferences.ui_scale + if zoom_in { 0.1 } else { -0.1 }).clamp(0.5, 2.5); + } + } + } + // Scaling while the pointer is held moves the slider under the pointer, feeding a + // different value back into it. Commit the layout change after the drag ends. + let z = app.preferences.ui_scale.clamp(0.5, 2.5); + if z.is_finite() && !ctx.input(|i| i.pointer.any_down()) && (ctx.zoom_factor() - z).abs() > 1e-3 { + ctx.set_zoom_factor(z); + } +} + +/// The network locations the files a design names may be on follow the preferences. +pub fn apply_network(p: &Prefs) { + solidcraft_engine::io::vfs::set_network_policy(solidcraft_engine::io::vfs::NetworkPolicy { + allow_all: p.network_locations, + hosts: p.network_hosts.clone(), + }); +} + +/// A new, empty design takes the preferred units (not an undo step, not a change to save). +/// Callers: a launch with no file, New on a design that is already empty, `file.new`, and the +/// blank design left when the last tab closes. A design that already has features is unchanged. +pub fn apply_new_design(app: &mut SolveApp) { + apply_new_design_units(app, &app.preferences.default_units.clone()); +} + +/// The new-design preference also applies to the blank, unsaved design already open. +fn default_units_changed(app: &mut SolveApp) { + if crate::documents::active_is_blank(app) { + apply_new_design(app); + } +} + +/// Explicit units for a new-design tile; the user's default preference stays unchanged. +pub(crate) fn apply_new_design_units(app: &mut SolveApp, units: &str) { + if app.session.doc.features.is_empty() && app.session.doc.units != units { + let saved = !app.session.is_dirty(); + if app.session.execute("document.units", &json!({ "units": units })).is_ok() { + app.session.undo.pop(); + if saved { + app.session.mark_saved(); + } + } + } +} + +/// The autosave interval follows `app.autosave_minutes` (0: off). +pub fn set_autosave(app: &mut SolveApp) { + let m = app.autosave_minutes; + if let Some(a) = app.autosave.as_mut() { + a.interval = if m > 0.0 { std::time::Duration::from_secs_f64(m * 60.0) } else { std::time::Duration::from_secs(u64::MAX / 4) }; + } +} + +/// Which navigation dragging `button` with `mods` held does under the preset. +pub fn nav_mode(app: &SolveApp, button: NavButton, mods: Modifiers) -> Option { + // With mouse gestures on, the right button opens the ring of tools instead of orbiting. + if button == NavButton::Right && crate::mouse_gesture::active(app) { + return None; + } + let mode = nav_preset(&app.preferences.nav).mode(button, mods); + // "Right drag orbits" off leaves the right button to the context menu (#6492). + if button == NavButton::Right && mode == Some(NavMode::Orbit) && !app.preferences.right_drag_orbits { + return None; + } + mode +} + +/// +1, or −1 when horizontal scrolling pans the other way (#2007). +pub fn pan_sign_x(app: &SolveApp) -> f32 { + if app.preferences.pan_reverse_x { -1.0 } else { 1.0 } +} + +/// +1, or −1 when vertical scrolling pans the other way. +pub fn pan_sign_y(app: &SolveApp) -> f32 { + if app.preferences.pan_reverse_y { -1.0 } else { 1.0 } +} + +/// +1, or −1 when Shift with two-finger scrolling orbits the other way (#8410). +pub fn orbit_sign(app: &SolveApp) -> f64 { + if app.preferences.orbit_reverse { -1.0 } else { 1.0 } +} + +/// Whether the configured suppress-snap chord is held. +pub fn suppress_sketch_snap_held(app: &SolveApp, m: Modifiers) -> bool { + let c = app.preferences.suppress_sketch_snap; + let held = crate::tool_modifiers::Held::from_modifiers(m); + // Classic default (`CTRL_ALT`): Ctrl/Cmd **or** Alt/Option each suppress snap. + // A single-key preference keeps the usual AtLeast match for that key only. + if c == ModifierCombo::CTRL_ALT { + return held.primary || held.alt; + } + c.held(m) +} + +/// Primary always frees manipulator arrows; Alt/Option also frees when `manipulator_free_alt` is on. +pub fn manipulator_free_held(app: &SolveApp, m: Modifiers) -> bool { + use crate::tool_modifiers::Held; + let held = Held::from_modifiers(m); + held.primary || (app.preferences.manipulator_free_alt && held.alt) +} + +/// +1, or −1 when the wheel zooms the other way. +pub fn zoom_sign(app: &SolveApp) -> f64 { + if app.preferences.zoom_reverse { -1.0 } else { 1.0 } +} + +/// The model point under a screen position: on a face, vertex, edge or sketch curve, the point +/// the cursor is on (on an edge or a curve too, not its middle, which can be far off along a long +/// one). Over empty space: the centre of the visible bodies and sketches (what Fit frames), or +/// the view's centre when nothing is visible. +pub(crate) fn pivot_under(app: &SolveApp, proj: &crate::viewport::Proj, at: Pos2) -> Vec3 { + use crate::viewport::Hit; + for h in crate::viewport::pick(app, proj, at) { + match h { + Hit::Face { point, .. } | Hit::Vertex { point, .. } | Hit::Edge { point, .. } | Hit::SketchCurve { point, .. } => { + return point; + } + _ => {} + } + } + // Over empty space: the middle of the bodies in view, not of everything shown (#2616). + if let Some(c) = crate::viewport::in_view_centre(app, proj) { + return c; + } + let b = crate::viewport::view_bounds(app); + if b.is_empty() { app.cam.target } else { b.center() } +} + +/// A plain number typed into a field, with a decimal point or a decimal comma (#1347): "2.5" +/// and "2,5" are both 2.5, as a numeric keypad types either depending on the locale. Spaces are +/// ignored and "−" is a minus, as in egui's own parser. A comma beside a point ("1.234,5") or a +/// second comma is not guessed at: the text is not a number. +pub fn parse_number(text: &str) -> Option { + let t: String = text.chars().filter(|c| !c.is_whitespace()).map(|c| if c == '\u{2212}' { '-' } else { c }).collect(); + let t = if !t.contains('.') && t.matches(',').count() == 1 { t.replacen(',', ".", 1) } else { t }; + t.parse::().ok().filter(|v| v.is_finite()) +} + +// Existing callers retain their numeric-editor API; kit owns the widget. + +/// A length typed into a field, in millimetres: a bare number is in the design's units (`scale` +/// units per millimetre); an explicit unit ("10 mm", "0.5 in", "2 cm + 3 mm") is honoured. +pub fn parse_length_mm(text: &str, scale: f64) -> Option { + use solidcraft_engine::doc::expr; + if !(scale.is_finite() && scale > 0.0) { + return None; + } + let defaults = expr::Defaults { len: 1.0 / scale, ..expr::Defaults::default() }; + let no_params = |n: &str| Err(solidcraft_engine::doc::DocError::Expr(format!("unknown parameter `{n}`"))); + let value = expr::eval_with_defaults(text.trim(), &no_params, defaults).ok()?.to_kind_in(expr::Kind::Length, defaults).ok()?; + value.is_finite().then_some(value) +} + +/// A length, area (`power` 2) or volume (3) given in millimetres, shown in the design's units +/// with the length precision. +pub fn show_mm(app: &SolveApp, v: f64, power: i32) -> String { + let (k, u) = unit_scale(&app.session.doc.units); + let sup = match power { + 2 => "²", + 3 => "³", + _ => "", + }; + let value = v * k.powi(power); + format!("{:.*} {u}{sup}", length_precision(value, &app.session.doc.units, app.preferences.length_decimals), value) +} + +/// Numbers in millimetres, in the design's units without the unit name. +pub fn show_mm_bare(app: &SolveApp, v: f64) -> String { + length_number(v, &app.session.doc.units, app.preferences.length_decimals) +} + +/// The window system choices (`Prefs::window_system`, #3083). +pub const WINDOW_SYSTEMS: &[&str] = &["auto", "wayland", "x11"]; +/// winit's issue for dropping files onto a window on native Wayland, which the note links to. +pub const WAYLAND_DROP_ISSUE: &str = "https://github.com/rust-windowing/winit/issues/1881"; + +/// Linux: Graphics › Window system (#3083). It applies at the next start; the note under it says +/// which one is running now, and when native Wayland is in use or chosen, that some features are +/// limited there, linking to [`WAYLAND_DROP_ISSUE`]. +#[cfg(target_os = "linux")] +fn window_system_row(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let label = |id: &str| crate::i18n::tr(&format!("ui.window_system_{id}")).to_string(); + let labels: Vec<_> = WINDOW_SYSTEMS.iter().copied().map(label).collect(); + let labels: Vec<_> = labels.iter().map(String::as_str).collect(); + // The note below says that it applies after a restart, and which one runs now. + let response = ui.allocate_ui_with_layout(egui::vec2(t.form_card_width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { + let mut selected = WINDOW_SYSTEMS.iter().position(|id| *id == app.preferences.window_system).unwrap_or(0); + if ui_kit::segmented(ui, &mut selected, &labels, ui_kit::Segments::default()) + && let Some(id) = WINDOW_SYSTEMS.get(selected) + { + app.preferences.window_system = (*id).into(); + } + }); + crate::scenario::publish_handle("prefs:window_system", response.response.rect.center()); + let now = app.services.window_system.map(label); + let text = match &now { + Some(now) => crate::i18n::format("settings.window_system_note_now", &[("now", now)]), + None => app.tr("settings.msaa_applies_on_restart").to_string(), + }; + ui_kit::text(ui, &text, ui_kit::Text::Hint("window_system")); + let choice = app.preferences.window_system.as_str(); + if choice == "wayland" || (choice == "auto" && app.services.window_system == Some("wayland")) { + ui.horizontal_wrapped(|ui| { + ui.label(egui::RichText::new(app.tr("settings.window_system_wayland_limited")).size(t.font_small).color(t.warning)); + ui.hyperlink_to(egui::RichText::new(app.tr("settings.window_system_details")).size(t.font_small), WAYLAND_DROP_ISSUE); + }); + } +} + +/// Write the anti-aliasing and window system settings where the host reads them at start (neither +/// can change while the window is open). +fn save_graphics(app: &SolveApp) { + if let Some(path) = &app.services.graphics_path { + // Other settings in the file (the graphics `backend`) stay as they are. + let mut graphics = std::fs::read_to_string(path) + .ok() + .and_then(|s| serde_json::from_str::(&s).ok()) + .filter(serde_json::Value::is_object) + .unwrap_or_else(|| json!({})); + graphics["msaa"] = json!(app.preferences.msaa); + graphics["window_system"] = json!(app.preferences.window_system); + graphics["adapter"] = json!(app.preferences.graphics_adapter); + let _ = std::fs::write(path, graphics.to_string()); + } +} + +/// At start, reflect a confirmed startup fallback in Graphics, or reset an unsupported +/// saved count to the supported default. The compatibility hint keeps higher choices +/// available for another try; a probe result alone does not overwrite the saved choice. +pub fn check_msaa(app: &mut SolveApp, requested: u32) { + if app.msaa_compatibility { + app.preferences.msaa = 1; + return; + } + let supported = &app.msaa_supported; + if requested <= 1 || supported.is_empty() || supported.contains(&requested) { + return; + } + let default = Prefs::default().msaa; + let reset = supported.iter().copied().filter(|&n| n <= default).max().unwrap_or(1); + let supported = supported.clone(); + app.preferences.msaa = reset; + save_graphics(app); + app.settings_reset.push(SettingReset::Msaa { requested, reset, supported }); +} + +/// A setting put back at start because it would keep SolidCraft from starting. +#[derive(Clone, Debug, PartialEq)] +pub enum SettingReset { + /// Anti-aliasing samples the graphics device can't render with. + Msaa { requested: u32, reset: u32, supported: Vec }, +} + +impl SettingReset { + /// The line the notice shows, in the current interface language. + pub fn message(&self) -> String { + match self { + SettingReset::Msaa { requested, reset, supported } => { + let setting = format!("{} › {}", crate::i18n::tr("ui.graphics"), crate::i18n::tr("ui.anti_aliasing")); + let supported = supported.iter().map(|n| format!("{n}")).collect::>().join("×, ") + "×"; + crate::i18n::format( + "settings.msaa_reset", + &[("setting", &setting), ("requested", &requested.to_string()), ("reset", &reset.to_string()), ("supported", &supported)], + ) + } + } + } +} + +/// The Preferences window can't be folded (`collapsible(false)`), but 0.14 and 0.15 folded it +/// when a font was picked, and egui keeps that in the saved window state: it then opened as its +/// title bar alone, for good (#1800). Unfold it. +fn unfold(ctx: &egui::Context) { + if let Some(mut body) = egui::collapsing_header::CollapsingState::load(ctx, egui::Id::new("sc_prefs").with("collapsing")) + && !body.is_open() + { + body.set_open(true); + body.store(ctx); + } +} + +pub fn show(app: &mut SolveApp, ctx: &egui::Context) { + // File › Keyboard Shortcuts and Help › Keyboard Shortcuts open this dialog at that page. + if app.keymap.open { + app.keymap.open = false; + open_at(app, PAGE_SHORTCUTS); + } + app.prefs_window.import_tile = None; + if !app.prefs_window.open { + app.prefs_window.filter.clear(); + app.prefs_window.search_from = None; + app.prefs_window.land_on = None; + app.prefs_window.reveal = None; + crate::prefs_search::set_reveal(ctx, None); + app.prefs_window.snapshot = None; + // A question left up when the dialog closed is not still asked when it opens again. + app.space_mouse.restore_pending = false; + // Calibration opens from here and ends with it, so the cap moves the view again. + app.space_mouse.calibrating = None; + return; + } + if app.prefs_window.snapshot.is_none() { + app.crashes.refresh(); + app.prefs_window.snapshot = Some(Snapshot::take(app)); + } + unfold(ctx); + if let Some(reveal) = &app.prefs_window.reveal + && crate::now_ms() > reveal.until + { + app.prefs_window.reveal = None; + } + let sink = crate::prefs_search::shift_key_sink(ctx); + crate::prefs_search::set_key_sink_prev(ctx, sink); + let mut button: Option<&str> = None; + let before = app.preferences.clone(); + let capturing = crate::keymap::capturing(app); + let pending = apply_pending(app); + let window = ui_kit::Window::new(egui::Id::new("sc_prefs"), "settings", app.tr("ui.preferences")) + .cards(10.0 / 3.0) + .page_rows(24.0) + .page_padding(egui::Margin { + left: (Tokens::get().space_16 + Tokens::get().space_4) as i8, + right: (Tokens::get().space_16 + Tokens::get().space_4) as i8, + top: Tokens::get().space_6 as i8, + bottom: (Tokens::get().space_16 + Tokens::get().space_4) as i8, + }) + .fields() + .actions("OK", "Cancel", Some("Apply")) + .apply_enabled(pending); + let window = if capturing { window.keep_open_on_escape() } else { window }; + let mut selected = app.prefs_window.section; + let (closed, action) = window.show_pages_with_header(ctx, &mut selected, WINDOW_PAGES, app, search_header, clear_search, |ui| { + if ui_kit::button(ui, crate::i18n::tr("ui.restore_defaults"), ui_kit::Button::Normal) + .on_hover_text(crate::i18n::tr("ui.reset_the_settings_on_this_page")) + .clicked() + { + button = Some("defaults"); + } + }); + if let Some(rect) = crate::scenario::rect_of("dialog:page_body") { + crate::scenario::publish_rect("prefs:page_body", rect); + } + for name in ["window", "footer", "ok", "apply", "cancel"] { + if let Some(rect) = crate::scenario::rect_of(&format!("dialog:{name}")) { + crate::scenario::publish_target(&format!("prefs:{name}"), rect); + } + } + crate::space_mouse_calibration::show(app, ctx); + if let Some(rect) = crate::scenario::rect_of("dialog:footer:actions") { + crate::scenario::publish_rect("prefs:actions", rect); + } + button = match action { + ui_kit::Action::Ok => Some("ok"), + ui_kit::Action::Apply => Some("apply"), + ui_kit::Action::Cancel => Some("cancel"), + ui_kit::Action::None => button, + }; + if app.preferences.msaa != before.msaa + || app.preferences.window_system != before.window_system + || app.preferences.graphics_adapter != before.graphics_adapter + { + save_graphics(app); + } + if app.preferences.up_axis != before.up_axis { + up_axis_changed(app); + } + match button { + Some("defaults") => defaults(app, app.prefs_window.section), + Some("apply") => app.prefs_window.snapshot = Some(Snapshot::take(app)), + Some("ok") => close(app, false), + Some("cancel") => close(app, true), + _ if closed => close(app, true), + _ => {} + } + // The footer was drawn before this frame's edits (and before an Apply): show Apply's new + // state on the next frame rather than at the next input. + if app.prefs_window.open && apply_pending(app) != pending { + ctx.request_repaint(); + } +} + +/// Close the dialog; `revert`: put back what was there when it opened (Cancel, Esc, ×). +pub(crate) fn close(app: &mut SolveApp, revert: bool) { + if let Some(s) = app.prefs_window.snapshot.take() + && revert + { + let up = app.preferences.up_axis.clone(); + s.restore(app); + if app.preferences.up_axis != up { + up_axis_changed(app); + } + } + app.prefs_window.open = false; + app.prefs_window.filter.clear(); + app.prefs_window.search_from = None; + app.prefs_window.land_on = None; + app.prefs_window.reveal = None; + app.keymap.read_only = false; + crate::keymap::stop_capture(app); +} + +/// The default orientation changed: the view turns to match. +fn up_axis_changed(app: &mut SolveApp) { + use solidcraft_engine::render::UpAxis; + app.prefs_window.applied_up = Some(app.preferences.up_axis.clone()); + let up = if app.preferences.up_axis.eq_ignore_ascii_case("y") { UpAxis::Y } else { UpAxis::Z }; + if app.ui.up_axis != up || app.cam.up != up { + app.set_up_axis(up); + } +} + +/// One page of the dialog. Inputs share the kit's aligned rows and tokenised controls. +/// A search draws every page and keeps the controls that match. +fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { + let _search = crate::prefs_search::begin(ui, &app.prefs_window.filter); + if crate::prefs_search::querying(ui) { + // Paint only the pages that match. A first pass is invisible, so the 3D mouse rows and the + // agent list cannot draw on top of the setting that did match. + let mut keep = vec![false; WINDOW_PAGES.len()]; + for (index, item) in WINDOW_PAGES.iter().enumerate() { + crate::prefs_search::begin_page(ui, index, crate::i18n::tr(item.label)); + let before = crate::prefs_search::hits(ui); + let mut probe = crate::prefs_search::detached_child(ui, ("prefs-search-probe", index), true); + draw_page(app, &mut probe, index, t); + keep[index] = crate::prefs_search::hits(ui) > before; + } + crate::prefs_search::rewind_search_layout(ui); + for (index, item) in WINDOW_PAGES.iter().enumerate() { + if !keep.get(index).copied().unwrap_or(false) { + continue; + } + crate::prefs_search::begin_page(ui, index, crate::i18n::tr(item.label)); + let before = crate::prefs_search::hits(ui); + let mut child = crate::prefs_search::detached_child(ui, ("prefs-search-page", index), false); + draw_page(app, &mut child, index, t); + crate::prefs_search::commit_search_child(ui, &child, before); + } + if crate::prefs_search::hits(ui) == 0 { + ui.label(egui::RichText::new(crate::i18n::tr("prefs.search_empty")).size(t.font_body).color(t.form_dim)); + } + } else { + let label = WINDOW_PAGES.get(app.prefs_window.section).map(|item| crate::i18n::tr(item.label)).unwrap_or(""); + crate::prefs_search::begin_page(ui, app.prefs_window.section, label); + draw_page(app, ui, app.prefs_window.section, t); + } + crate::prefs_search::store_nav(ui); +} + +fn draw_page(app: &mut SolveApp, ui: &mut egui::Ui, index: usize, t: &Tokens) { + match index { + PAGE_SHORTCUTS => crate::keymap::page(app, ui), + PAGE_AI => crate::agent_chat::settings::page(app, ui), + PAGE_PLUGINS => crate::plugins::page(app, ui), + PAGE_GENERAL => general::show(app, ui), + PAGE_INTERFACE => interface::interface(app, ui, t), + PAGE_DESIGN => design::show(app, ui), + PAGE_NAVIGATION => navigation::show(app, ui, t), + PAGE_GRAPHICS => { + graphics::show(app, ui); + cpu_progressive_advanced_preferences(app, ui); + } + PAGE_SKETCH => sketch::show(app, ui), + _ => {} + } +} + +fn cpu_progressive_advanced_preferences(app: &mut SolveApp, ui: &mut egui::Ui) { + let title = app.tr("prefs.cpu_render_advanced").to_string(); + ui_kit::section(ui, "prefs_cpu_render_advanced", &title, false, |ui| { + let response = setting::render_cpu_progressive_every_pass(app, ui) + .on_hover_text(app.tr("prefs.render_cpu_progressive_every_pass_help")); + crate::scenario::publish_target("prefs:render-cpu-progressive-every-pass", response.rect); + let response = setting::render_cpu_interactive_explicit_sampling(app, ui) + .on_hover_text(app.tr("prefs.render_cpu_interactive_explicit_sampling_help")); + crate::scenario::publish_target("prefs:render-cpu-interactive-explicit-sampling", response.rect); + }); +} + +fn page_index(name: &str) -> Option { + match name.to_ascii_lowercase().as_str() { + "selection" | "sketch & selection" | "sketch and selection" => Some(PAGE_SKETCH), + "interface/navigation bar" => Some(PAGE_INTERFACE), + "assistant" => Some(PAGE_AI), + "shortcuts" => Some(PAGE_SHORTCUTS), + _ => PAGES.iter().position(|x| x.eq_ignore_ascii_case(name)), + } +} + +/// The 3D mouse's settings under Navigation, drawn with the same settings kit as the sections above +/// it: whether it moves the view and shows in it, where the picture goes, its speed, the driver and +/// calibration, each axis, the picture with its dead zone, and what its buttons do. A section like the +/// others, so it folds with its header and stays as the user last left it. +fn space_mouse_section(app: &mut SolveApp, ui: &mut egui::Ui) { + ui_kit::settings_section(ui, "space_mouse", crate::i18n::tr("ui.3d_mouse_section"), |ui| space_mouse_rows(app, ui)); +} + +/// The label column the Navigation page's forms share (`prefs/navigation.rs`). +const FORM_LABEL_WIDTH: f32 = 150.0; + +fn space_mouse_rows(app: &mut SolveApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + // The two checkboxes sit in the two-column grid Wheel and trackpad uses (`navigation.rs`). + let width = (ui.available_width() - (t.space_16 + t.space_4)) * 0.5; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = t.space_16 + t.space_4; + ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.horizontal_wrapped(|ui| { + setting::space_mouse_enabled(app, ui); + let device = app.space_mouse.device.as_ref(); + let saved = device.is_some_and(|device| app.preferences.space_mouse_calibrations.contains_key(device)); + if let Some(device) = device { + let state = app.tr(if saved { "ui.3d_mouse_calibrated" } else { "ui.3d_mouse_not_calibrated" }); + ui_kit::settings_badge(ui, &format!("{state} · {device}"), !saved); + } + }); + }); + ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { + setting::space_mouse_in_view(app, ui).on_hover_text(crate::i18n::tr("ui.3d_mouse_show_in_view_tip")); + }); + }); + // Where the picture goes, a choice that waits on the checkbox above. + let names: Vec<(SpaceMouseGhost, String)> = [ + (SpaceMouseGhost::LeftViewport, "ui.3d_mouse_ghost_left_viewport"), + (SpaceMouseGhost::RightViewport, "ui.3d_mouse_ghost_right_viewport"), + (SpaceMouseGhost::LeftWindow, "ui.3d_mouse_ghost_left_window"), + ] + .map(|(position, key)| (position, app.tr(key).to_owned())) + .into(); + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + ui_kit::row(ui, crate::i18n::tr("ui.3d_mouse_ghost_position"), |ui| { + let (in_view, position) = (app.preferences.space_mouse_in_view, &mut app.preferences.space_mouse_ghost_position); + ui.add_enabled_ui(in_view, |ui| { + ui_kit::settings_control_width(ui, AXIS_DRIVEN_WIDTH, |ui| { + let current = names.iter().find(|(choice, _)| choice == position).map_or("", |(_, name)| name.as_str()); + ui_kit::dropdown_menu(ui, "sc_space_mouse_ghost", current, |ui| { + for (choice, name) in &names { + if ui_kit::list_picker(ui, name, name, choice == position).clicked() { + *position = *choice; + } + } + }); + }); + }); + }); + ui_kit::row(ui, app.tr("prefs.overall_speed"), |ui| { + ui.add_enabled_ui(app.preferences.space_mouse_enabled, |ui| { + ui_kit::slider( + ui, + &mut app.preferences.space_mouse_speed, + 0.25..=5.0, + ui_kit::Slider { step: Some(0.05), format: |value| format!("{value:.2}×"), ..Default::default() }, + ); + }); + }); + ui_kit::row(ui, app.tr("ui.3d_mouse_calibration"), |ui| { + let device = app.space_mouse.device.clone(); + let saved = device.as_ref().is_some_and(|device| app.preferences.space_mouse_calibrations.contains_key(device)); + ui.add_enabled_ui(app.preferences.space_mouse_enabled && device.is_some(), |ui| { + if ui_kit::button(ui, app.tr("ui.3d_mouse_calibrate"), ui_kit::Button::Normal) + .on_hover_text(app.tr("ui.3d_mouse_calibrate_tip")) + .on_disabled_hover_text(app.tr(if app.space_mouse.device.is_none() { + "ui.3d_mouse_calibrate_wait" + } else { + "ui.3d_mouse_calibrate_tip" + })) + .clicked() + { + crate::space_mouse_calibration::start(app); + } + if saved + && ui_kit::button(ui, app.tr("ui.3d_mouse_forget"), ui_kit::Button::Normal).clicked() + && let Some(device) = &device + { + app.preferences.space_mouse_calibrations.remove(device); + } + }); + let not_allowed = found_but_not_allowed(app.space_mouse.drivers); + // With a device, the badge beside the toggle above says this. + if device.is_some() { + return; + } + let status = if not_allowed { + app.tr("ui.3d_mouse_denied_short") + } else if waiting_for_a_record(app.space_mouse.drivers) { + app.tr("ui.3d_mouse_calibrate_wait") + } else { + app.tr("ui.3d_mouse_none") + }; + let status_line = ui_kit::text(ui, status, ui_kit::Text::Report("calibration_status", false)); + // Nothing confirmed yet (none found, or waiting for the first record): a hint to try, as a + // tooltip here and, while a reader is waiting for the first record, as a line below. + if device.is_none() && !not_allowed { + status_line.on_hover_text(app.tr("ui.3d_mouse_wiggle")); + } + }); + if app.space_mouse.device.is_none() { + if found_but_not_allowed(app.space_mouse.drivers) { + // Wiggling will not help: the device is there and SolidCraft may not read it. + hint_under_controls(ui, app.tr("ui.3d_mouse_denied"), "space_mouse_denied"); + } else { + hint_under_controls(ui, app.tr("ui.3d_mouse_wiggle"), "space_mouse_wiggle"); + } + } + }); + // A device whose own app drives the view instead (the navigation bridge). + ui_kit::divider(ui, "nav_bridge"); + navigation::nav_bridge(app, ui); + // The rarely needed settings sit behind one disclosure, closed until the reader opens it. + ui_kit::section(ui, "space_mouse_advanced", crate::i18n::tr_label("Advanced"), false, |ui| { + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + // Only where the reader has seen the choice: Linux, with spacenavd and the device both there. + if let Some(present) = app.space_mouse.drivers.filter(|present| present.spacenavd || (present.direct && !present.denied)) { + let [label, auto, direct, only_spacenavd, only_direct] = + ["driver", "driver_auto", "driver_direct", "driver_only_spacenavd", "driver_only_direct"] + .map(|key| app.tr(&format!("ui.3d_mouse_{key}")).to_owned()); + let driver = &mut app.preferences.space_mouse_driver; + ui_kit::row(ui, &label, |ui| match (present.spacenavd, present.direct) { + (true, true) => { + let name = |driver| match driver { + SpaceMouseDriver::Automatic => auto.as_str(), + SpaceMouseDriver::Spacenavd => "spacenavd", + SpaceMouseDriver::Direct => direct.as_str(), + }; + ui_kit::settings_control_width(ui, AXIS_DRIVEN_WIDTH, |ui| { + ui_kit::dropdown_menu(ui, "sc_space_mouse_driver", name(*driver), |ui| { + for choice in SpaceMouseDriver::ALL { + if ui_kit::list_picker(ui, name(choice), name(choice), *driver == choice).clicked() { + *driver = choice; + } + } + }); + }); + } + (true, false) => { + ui_kit::text(ui, &only_spacenavd, ui_kit::Text::Hint("space_mouse_driver")); + } + (false, _) => { + ui_kit::text(ui, &only_direct, ui_kit::Text::Hint("space_mouse_driver")); + } + }); + } + // The setting says what was asked for; this says what is read when that is not it: Direct or + // Automatic with the daemon read because the device itself could not be opened. + if let Some(present) = app.space_mouse.drivers + && present.spacenavd + && present.direct + && app.preferences.space_mouse_driver != SpaceMouseDriver::Spacenavd + && app.space_mouse.device.as_deref() == Some("spacenavd") + { + hint_under_controls(ui, app.tr("ui.3d_mouse_driver_fallback"), "space_mouse_driver_fallback"); + } + let enabled = app.preferences.space_mouse_enabled; + let (label, tip) = (app.tr("ui.3d_mouse_dead_zone").to_owned(), app.tr("ui.3d_mouse_dead_zone_tip").to_owned()); + let device = app.space_mouse.device.clone(); + if let Some(calibration) = device.and_then(|device| app.preferences.space_mouse_calibrations.get_mut(&device)) { + ui_kit::row(ui, &label, |ui| { + ui.add_enabled_ui(enabled, |ui| { + ui_kit::slider( + ui, + &mut calibration.dead_zone_share, + 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE, + ui_kit::Slider { step: Some(0.01), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }, + ) + .on_hover_text(tip); + }); + }); + } + }); + ui_kit::divider(ui, "space_mouse_axes"); + // Rows say what they do to the view, through the mapping navigation uses; the choices + // are the device's calibrated motions. Neither names a kind of device. + let mapping = app.space_mouse.mapping; + let rows: Vec<(String, bool)> = (0..6) + .map(|row| { + let label = crate::space_mouse::row_label(mapping, row); + let text = crate::i18n::Locale::for_language(&app.preferences.language).format(label, &[("n", &(row + 1).to_string())]); + (text, label == "ui.3d_mouse_view_off") + }) + .collect(); + let driven_by = app.tr("ui.3d_mouse_driven_by").to_owned(); + let off_tip = app.tr("ui.3d_mouse_view_off_tip").to_owned(); + let motions: Vec = crate::space_mouse::MOTIONS.iter().map(|motion| app.tr(motion).to_owned()).collect(); + // The axes are a table of their own: each row is a live meter of the motion that drives that + // view axis, then its Invert, Speed and the motion choice. + let enabled = app.preferences.space_mouse_enabled; + let raw: [i16; 6] = app.space_mouse.raw.into(); + // Frames come on input, so a reading that moved since the last one gets a frame to show it. + let seen = ui.id().with("space_mouse_meter_raw"); + let before = ui.data_mut(|data| data.get_temp::<[i16; 6]>(seen)); + ui.data_mut(|data| data.insert_temp(seen, raw)); + if before.is_some_and(|before| before != raw) { + ui.ctx().request_repaint(); + } + let calibration = app.space_mouse.device.as_ref().and_then(|device| app.preferences.space_mouse_calibrations.get(device)); + let meters: [_; 6] = std::array::from_fn(|axis| axis_meter(calibration, raw, app.preferences.space_mouse_axis_source, axis)); + ui_kit::settings_axis_header(ui); + for (axis, (name, off)) in rows.iter().enumerate() { + ui.push_id(("space_mouse_axis", axis), |ui| { + let (value, zone) = meters[axis]; + let prefs = &mut app.preferences; + let (reverse, speed, source) = + (prefs.space_mouse_reverse.get_mut(axis), prefs.space_mouse_axis_speed.get_mut(axis), &mut prefs.space_mouse_axis_source); + ui_kit::settings_axis_row( + ui, + name, + value, + zone, + // Invert and speed do nothing on a row the driver turns off. The motion choice + // stays live, so a motion can still be swapped out of it. + |ui| { + ui.add_enabled_ui(enabled && !off, |ui| { + if let Some(reverse) = reverse { + ui_kit::checkbox(ui, crate::i18n::tr_label("Invert"), reverse); + } + }); + }, + |ui| { + ui.add_enabled_ui(enabled && !off, |ui| { + if let Some(speed) = speed { + ui_kit::settings_axis_gain(ui, speed); + } + }); + }, + |ui| { + ui.add_enabled_ui(enabled, |ui| { + let current = source.get(axis).copied().unwrap_or(axis); + let mut chosen = current; + ui_kit::dropdown_menu(ui, ("sc_space_mouse_source", axis), motions.get(current).map_or("", String::as_str), |ui| { + for (from, name) in motions.iter().enumerate() { + if ui_kit::list_picker(ui, name, name, chosen == from).clicked() { + chosen = from; + } + } + }) + .on_hover_text(if *off { &off_tip } else { &driven_by }); + if chosen != current { + crate::space_mouse::reassign(source, axis, chosen); + } + }); + }, + ); + }); + } + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + ui_kit::row(ui, "", |ui| { + let reassigned = app.preferences.space_mouse_axis_source != crate::space_mouse::SAME_AXES; + ui.add_enabled_ui(app.preferences.space_mouse_enabled && reassigned, |ui| { + if ui_kit::button(ui, app.tr("ui.3d_mouse_reset_axes"), ui_kit::Button::Normal).clicked() { + app.preferences.space_mouse_axis_source = crate::space_mouse::SAME_AXES; + } + }); + }); + // Restore this section's settings (after asking); the calibration, the button mapping and the + // test model are not touched. + if app.space_mouse.restore_pending { + // A short question on its own, not in a row (a row has one line's height and cut it off), so + // that it wraps to its whole height at any width; the buttons are under it. + hint_under_controls(ui, app.tr("ui.3d_mouse_restore_ask"), "space_mouse_restore_ask"); + ui_kit::row(ui, "", |ui| { + if ui_kit::button(ui, app.tr("ui.3d_mouse_restore"), ui_kit::Button::Normal).clicked() { + restore_space_mouse_defaults(app); + app.space_mouse.restore_pending = false; + } + if ui_kit::button(ui, app.tr("ui.cancel"), ui_kit::Button::Normal).clicked() { + app.space_mouse.restore_pending = false; + } + }); + } else { + ui_kit::row(ui, "", |ui| { + if ui_kit::button(ui, app.tr("ui.3d_mouse_restore"), ui_kit::Button::Normal).clicked() { + app.space_mouse.restore_pending = true; + } + }); + } + }); + // The calibrated device moving as it does, with the test model beside it, then its dead zones. + let (device, raw) = (app.space_mouse.device.clone(), app.space_mouse.raw.into()); + let (boat, motion, reverse) = (&mut app.space_mouse.boat, app.space_mouse.motion, (app.preferences.zoom_reverse, app.preferences.free_orbit)); + if let Some(calibration) = device.as_ref().and_then(|device| app.preferences.space_mouse_calibrations.get_mut(device)) { + ui_kit::divider(ui, "space_mouse_picture"); + // Under each circle's axes, what the view does with them: the rows' own labels. + let stories = crate::space_mouse::stories(&app.preferences.language, mapping, app.preferences.space_mouse_axis_source); + let help = crate::i18n::tr("ui.3d_mouse_circles_help").to_string(); + let pads = |ui: &mut egui::Ui| { + crate::space_mouse_calibration::dead_zone_pads(ui, calibration, raw, false, &stories); + ui_kit::text(ui, &help, ui_kit::Text::Hint("space_mouse_circles_help")); + }; + picture_and_boat(ui, boat, motion, reverse, true, |ui| crate::space_mouse_model::live(ui, calibration, raw), pads); + } else if device.is_some() { + // Not calibrated: the test model alone. + ui_kit::divider(ui, "space_mouse_picture"); + picture_and_boat(ui, boat, motion, reverse, false, |_| {}, |_| {}); + } + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + hint_under_controls(ui, crate::i18n::tr_label("Move and rotate the view together; sketches use pan and zoom only."), "space_mouse"); + }); + ui_kit::divider(ui, "space_mouse_buttons"); + space_mouse_buttons(app, ui); + }); +} + +/// A hint in the control column of the forms above and below it, as the form rows' controls are, +/// not at the section's left edge. +fn hint_under_controls(ui: &mut egui::Ui, text: &str, key: &str) { + let indent = FORM_LABEL_WIDTH.min(ui.available_width() * 0.6) + Tokens::get().space_14; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.add_space(indent); + ui_kit::text(ui, text, ui_kit::Text::Hint(key)); + }); +} + +/// The width of the "driven by" choice. +const AXIS_DRIVEN_WIDTH: f32 = 140.0; + +/// Where the motion that drives view axis `axis` sits, as a share of its full travel (calibrated +/// when the device has a calibration, else the raw reading over full scale), and the share of that +/// travel which reads as no motion on each side, for the live meter in its row. +fn axis_meter(calibration: Option<&solidcraft_space_mouse::Calibration>, raw: [i16; 6], source: [usize; 6], axis: usize) -> (f32, [f32; 2]) { + let from = source.get(axis).copied().unwrap_or(axis); + match calibration { + Some(calibration) => { + (calibration.travel(raw).get(from).copied().unwrap_or(0.0), calibration.dead_zone_shares().get(from).copied().unwrap_or_default()) + } + None => (f32::from(raw.get(from).copied().unwrap_or(0)) / f32::from(crate::space_mouse::FULL_SCALE), [0.0; 2]), + } +} + +/// Whether a reader is reachable (spacenavd's socket, or a 3D mouse hidraw lists) that has not yet +/// sent a record: the device is not confirmed until it does, so Preferences asks for a movement +/// instead of saying none was found. Nothing reachable at all is "none found". +fn waiting_for_a_record(drivers: Option) -> bool { + drivers.is_some_and(|present| present.spacenavd || (present.direct && !present.denied)) +} + +/// A 3D mouse is there but may not be opened, and nothing else is reachable (no spacenavd): asking for +/// a movement would wait forever, so Preferences says what is wrong instead. +fn found_but_not_allowed(drivers: Option) -> bool { + drivers.is_some_and(|present| present.denied && !present.spacenavd) +} + +/// Puts this section's settings back: the driver choice, the speed, each axis's invert and speed and +/// assignment, where the picture goes and whether it shows. Not the calibration (it has its own +/// Forget), the button mapping, the offered set, "never show again", "Navigate with the 3D mouse" or +/// the test model. +pub fn restore_space_mouse_defaults(app: &mut SolveApp) { + let d = Prefs::default(); + let p = &mut app.preferences; + p.space_mouse_driver = d.space_mouse_driver; + p.space_mouse_speed = d.space_mouse_speed; + p.space_mouse_reverse = d.space_mouse_reverse; + p.space_mouse_axis_speed = d.space_mouse_axis_speed; + p.space_mouse_axis_source = d.space_mouse_axis_source; + p.space_mouse_ghost_position = d.space_mouse_ghost_position; + p.space_mouse_in_view = d.space_mouse_in_view; +} + +/// The device's picture with the coordinate circles under it, and a box with a small model that +/// moves with the 3D mouse as the view does and a Reset button: to the right of the picture where +/// there is room, else under the circles. All stay inside the section at any width. +fn picture_and_boat( + ui: &mut egui::Ui, + boat: &mut Option, + motion: Option, + (reverse_zoom, free_orbit): (bool, bool), + has_picture: bool, + picture: impl FnOnce(&mut egui::Ui), + pads: impl FnOnce(&mut egui::Ui), +) { + const PICTURE_WIDTH: f32 = 200.0; + const BOAT_HEIGHT: f32 = 150.0; + const BOAT_MIN: f32 = 120.0; + const BOAT_MAX: f32 = 260.0; + let gap = Tokens::get().space_12; + let room = ui.available_width(); + let beside = has_picture && ui_kit::fits_steadily(ui, "boat_beside", PICTURE_WIDTH + gap + BOAT_MIN, room); + let width = if beside { (room - PICTURE_WIDTH - gap).min(BOAT_MAX) } else { room.min(BOAT_MAX) }; + let mut boat_and_reset = |ui: &mut egui::Ui| { + ui.vertical(|ui| { + crate::test_boat::show(ui, boat, motion, reverse_zoom, free_orbit, egui::vec2(width.max(0.0), BOAT_HEIGHT)); + if ui_kit::button(ui, crate::i18n::tr("ui.3d_mouse_reset_view"), ui_kit::Button::Normal).clicked() { + crate::test_boat::reset(boat); + } + }); + }; + // The coordinate circles stay under the device's picture, from its left edge; the test model is + // beside the picture where there is room, else under the circles. + if beside { + ui.horizontal(|ui| { + picture(ui); + boat_and_reset(ui); + }); + pads(ui); + } else { + picture(ui); + pads(ui); + boat_and_reset(ui); + } +} + +/// The 3D mouse's buttons, each with what it does: those that do something and any pressed since +/// the app started. A pressed one is marked in its row; Preferences doesn't run them. +fn space_mouse_buttons(app: &mut SolveApp, ui: &mut egui::Ui) { + let Some(device) = app.space_mouse.device.clone() else { + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + hint_under_controls(ui, crate::i18n::tr("ui.3d_mouse_buttons_no_device"), "space_mouse_buttons"); + }); + return; + }; + let mut jobs = crate::space_mouse::button_jobs(app, &device); + let bit = |number: u8| number.checked_sub(1).and_then(|index| 1_u32.checked_shl(u32::from(index))).unwrap_or(0); + let mut numbers: std::collections::BTreeSet = jobs.keys().copied().collect(); + numbers.extend((1..=32).filter(|&number| app.space_mouse.seen & bit(number) != 0)); + let mut changed = false; + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + hint_under_controls(ui, crate::i18n::tr("ui.3d_mouse_buttons_hint"), "space_mouse_buttons"); + for number in numbers { + let mut name = crate::i18n::format("ui.3d_mouse_button", &[("number", &number.to_string())]); + if app.space_mouse.buttons & bit(number) != 0 { + name.push_str(" ●"); + } + let current = jobs.get(&number).cloned(); + if let Some(choice) = ui_kit::row(ui, &name, |ui| button_job_picker(app, ui, number, current.as_ref())) { + changed = true; + match choice { + Some(job) => jobs.insert(number, job), + None => jobs.remove(&number), + }; + } + } + }); + if changed { + app.preferences.space_mouse_buttons.insert(device.clone(), jobs); + } + if app.preferences.space_mouse_buttons.contains_key(&device) { + ui_kit::settings_form(ui, FORM_LABEL_WIDTH, |ui| { + ui_kit::row(ui, "", |ui| { + if ui_kit::button(ui, crate::i18n::tr("ui.3d_mouse_buttons_reset"), ui_kit::Button::Normal).clicked() { + app.preferences.space_mouse_buttons.remove(&device); + } + }); + }); + } +} + +/// What a button job is called in its picker. +fn button_job_label(app: &SolveApp, job: Option<&crate::space_mouse::ButtonJob>) -> String { + use crate::space_mouse::{ButtonJob, ButtonKey}; + match job { + None => crate::i18n::tr("ui.3d_mouse_button_nothing").to_string(), + Some(ButtonJob::Settings) => crate::i18n::tr("ui.3d_mouse_button_settings").to_string(), + Some(ButtonJob::View(view)) => { + let mut name = view.clone(); + if let Some(first) = name.get_mut(0..1) { + first.make_ascii_uppercase(); + } + app.tr_label(&name).to_string() + } + Some(ButtonJob::Key(key)) => match key { + ButtonKey::Esc => "Esc", + ButtonKey::Shift => "Shift", + ButtonKey::Ctrl => "Ctrl", + ButtonKey::Alt => "Alt", + } + .to_string(), + Some(ButtonJob::Command(id)) => solidcraft_engine::find_command(id).map_or_else(|| id.clone(), |c| app.tr_label(c.label).to_string()), + } +} + +/// A job as the picker's value: what it is and, for a view, key or command, which. +fn button_job_value(job: Option<&crate::space_mouse::ButtonJob>) -> String { + use crate::space_mouse::ButtonJob; + match job { + None => "none".into(), + Some(ButtonJob::Settings) => "settings".into(), + Some(ButtonJob::View(view)) => format!("view:{view}"), + Some(ButtonJob::Key(key)) => format!("key:{key:?}"), + Some(ButtonJob::Command(id)) => format!("cmd:{id}"), + } +} + +/// A button's job, chosen from nothing, the 3D mouse settings, the views, the keys, then any +/// command, in the kit's searchable dropdown. `Some` with the new job when one is picked. +fn button_job_picker( + app: &SolveApp, + ui: &mut egui::Ui, + number: u8, + current: Option<&crate::space_mouse::ButtonJob>, +) -> Option> { + use crate::space_mouse::{ButtonJob, ButtonKey}; + let views = ["home", "fit", "top", "front", "right", "left", "back", "bottom"].map(|view| ButtonJob::View(view.into())); + let keys = [ButtonKey::Esc, ButtonKey::Shift, ButtonKey::Ctrl, ButtonKey::Alt].map(ButtonJob::Key); + let commands = solidcraft_engine::command_specs().into_iter().map(|spec| ButtonJob::Command(spec.id.into())); + let jobs: Vec> = + [None, Some(ButtonJob::Settings)].into_iter().chain(views.into_iter().chain(keys).chain(commands).map(Some)).collect(); + let entries: Vec<(String, String)> = jobs.iter().map(|job| (button_job_value(job.as_ref()), button_job_label(app, job.as_ref()))).collect(); + let options: Vec<_> = entries.iter().map(|(value, label)| ui_kit::SearchOption { value, label, handle: None }).collect(); + let filter_id = egui::Id::new(("sc_space_mouse_button_filter", number)); + let mut filter: String = ui.data_mut(|data| data.get_temp(filter_id).unwrap_or_default()); + let id = format!("sc_space_mouse_button_{number}"); + let chosen = ui_kit::searchable_dropdown(ui, &id, &button_job_label(app, current), &mut filter, &options, None, None); + ui.data_mut(|data| data.insert_temp(filter_id, filter)); + let chosen = chosen?; + jobs.into_iter().find(|job| button_job_value(job.as_ref()) == chosen) +} + +/// The control channel's `ui.prefs`: `open` (a page name) opens the dialog there, `button` +/// presses OK, Cancel, Apply or Restore Defaults, `stand_up: true` answers the stand-up offer, +/// dialog or note (`false` leaves the file as it is, like "Leave it"), `theme_import` (a theme file's JSON or +/// text) adds a theme and turns it on, `theme_remove` (an id) removes an imported one and +/// `theme_export: true` returns the theme on now as `theme_file`, `theme_follow` (a path, or +/// `""` to stop) follows a theme file on the desktop (#7573); any other keys set preferences. +/// `open: "Interface/Navigation bar"` opens Interface and scrolls to its bar editor. +/// Returns them all, the open page, the offer (and whether it is the note), the theme ids and the +/// followed file (`theme_followed`, `theme_follow_error`). +pub fn control(app: &mut SolveApp, p: &serde_json::Value) -> Result { + let mut rest = p.as_object().cloned().unwrap_or_default(); + if let Some(page) = rest.remove("open") { + let name = page.as_str().unwrap_or("General"); + let i = page_index(name).ok_or_else(|| format!("no page `{name}` ({})", PAGES.join(", ")))?; + open_at(app, i); + app.prefs_window.navbar_scroll = name.eq_ignore_ascii_case("Interface/Navigation bar"); + if app.prefs_window.snapshot.is_none() { + app.prefs_window.snapshot = Some(Snapshot::take(app)); + } + } + match rest.remove("stand_up").and_then(|v| v.as_bool()) { + Some(true) => crate::stand_up::stand_up(app)?, + Some(false) => crate::stand_up::leave(app), + None => {} + } + let imported = match rest.remove("theme_import") { + Some(v) => Some(import_theme(app, &v)?), + None => None, + }; + if let Some(id) = rest.remove("theme_remove") { + remove_theme(app, id.as_str().unwrap_or_default())?; + } + match rest.remove("theme_follow") { + Some(v) => set_theme_follow(app, &v, FOLLOW_AVAILABLE)?, + // Choosing a theme stops following a file, as clicking a theme tile does. + None if rest.contains_key("theme") => stop_following(app), + None => {} + } + let export = rest.remove("theme_export").and_then(|v| v.as_bool()).unwrap_or(false); + let button = rest.remove("button"); + let mut out = set(app, &serde_json::Value::Object(rest))?; + match button.as_ref().and_then(|b| b.as_str()) { + Some("ok") => close(app, false), + Some("cancel") => close(app, true), + Some("apply") => app.prefs_window.snapshot = Some(Snapshot::take(app)), + Some("defaults") => defaults(app, app.prefs_window.section), + Some(b) => return Err(format!("unknown button `{b}` (ok, cancel, apply, defaults)")), + None => {} + } + if button.is_some() { + out = serde_json::to_value(&app.preferences).map_err(|e| e.to_string())?; + } + if let Some(o) = out.as_object_mut() { + o.insert("dialog".into(), json!(app.prefs_window.open.then(|| PAGES.get(app.prefs_window.section).copied().unwrap_or_default()))); + o.insert("apply_enabled".into(), json!(apply_pending(app))); + o.insert("stand_up_offer".into(), json!(app.stand_up)); + o.insert("stand_up_note".into(), json!(app.stand_up.is_some() && app.stand_up_note)); + o.insert("dark".into(), json!(app.ui.dark)); + o.insert("viewport_dark".into(), json!(app.viewport_dark())); + o.insert("theme_ids".into(), json!(theme_choices(app).into_iter().map(|(id, _)| id).collect::>())); + let follow = &app.prefs_window.follow; + let followed = follow.path(&app.preferences.theme_follow); + o.insert("theme_followed".into(), json!((!followed.is_empty()).then_some(followed))); + o.insert("theme_follow_error".into(), json!(follow.error().filter(|_| !followed.is_empty()))); + if let Some(id) = imported { + o.insert("theme_imported".into(), json!(id)); + } + if export { + o.insert("theme_file".into(), current_theme_file(app)); + } + } + Ok(out) +} + +/// The saved 3D mouse calibrations that still read. One this version can't read (a hand edit, a +/// format from another release) is dropped on its own, with a log line, not with all the others. +fn calibrations_that_read<'de, D: serde::Deserializer<'de>>( + saved: D, +) -> Result, D::Error> { + let saved = std::collections::BTreeMap::::deserialize(saved)?; + Ok(saved + .into_iter() + .filter_map(|(device, calibration)| match serde_json::from_value(calibration) { + Ok(calibration) => Some((device, calibration)), + Err(error) => { + log::warn!("preferences: the 3D mouse calibration for `{device}` can't be read ({error}); reading the device as it reports"); + None + } + }) + .collect()) +} + +/// The saved set of devices that read as text; anything else in it is dropped, not the whole set. +fn devices_that_read<'de, D: serde::Deserializer<'de>>(saved: D) -> Result, D::Error> { + let saved = Vec::::deserialize(saved)?; + Ok(saved.into_iter().filter_map(|device| device.as_str().map(str::to_owned)).collect()) +} + +/// The saved button jobs that still read. A job this version doesn't know (from a newer release) +/// drops that button only, with a log line, not its device's other buttons or the other devices. +fn button_jobs_that_read<'de, D: serde::Deserializer<'de>>( + saved: D, +) -> Result>, D::Error> { + let saved = std::collections::BTreeMap::::deserialize(saved)?; + Ok(saved + .into_iter() + .filter_map(|(device, jobs)| { + let jobs = match jobs { + serde_json::Value::Object(jobs) => jobs, + _ => { + log::warn!("preferences: the 3D mouse buttons for `{device}` can't be read; using the defaults"); + return None; + } + }; + let jobs = jobs + .into_iter() + .filter_map(|(number, job)| { + let read = number.parse::().ok().and_then(|number| Some((number, serde_json::from_value(job).ok()?))); + if read.is_none() { + log::warn!("preferences: button {number} of the 3D mouse `{device}` can't be read; leaving it empty"); + } + read + }) + .collect(); + Some((device, jobs)) + }) + .collect()) +} + +/// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then +/// the imported ones. +fn theme_choices(app: &SolveApp) -> Vec<(String, String)> { + let modes = THEMES.iter().map(|(id, label)| ((*id).to_string(), crate::i18n::tr_label(label).to_string())); + let files = crate::theme_files::builtin().iter().chain(&app.preferences.custom_themes).map(|t| (t.id.clone(), t.name.clone())); + modes.chain(files).collect() +} + +/// Turn a theme on (a mode or a theme file's id); dark follows it. +fn select_theme(app: &mut SolveApp, id: &str) { + app.preferences.theme = id.to_string(); + match crate::theme_files::find(id, &app.preferences.custom_themes) { + Some(f) => app.ui.dark = f.base.is_dark(), + None if id != "system" => app.ui.dark = id == "dark", + None => {} + } +} + +/// Import a theme file (its text, or its JSON) into the preferences and turn it on; returns +/// the id it is kept under. +/// Import a theme file's text, from a file, a paste or a drop, and say what happened in the status bar. +fn import_theme_text(app: &mut SolveApp, text: Result) { + match text.and_then(|text| import_theme(app, &serde_json::Value::String(text))) { + Ok(id) => { + let name = crate::theme_files::find(&id, &app.preferences.custom_themes).map(|t| t.name.clone()).unwrap_or(id); + app.set_status(format!("Theme imported: {name}"), false); + } + Err(e) => app.set_status(format!("Theme import: {e}"), true), + } +} + +/// Text that is meant as a theme file: a JSON object naming the theme format. Anything else +/// pasted while Preferences is open keeps its usual meaning. +fn looks_like_theme(text: &str) -> bool { + text.trim_start().starts_with('{') && text.contains(crate::theme_files::FORMAT) +} + +/// Ctrl/Cmd+V on the Interface page with a theme file's text on the clipboard imports it, like +/// Import… with a file (#8226). Called before the global Copy and Paste shortcuts, which would +/// otherwise paste copied components; the paste is taken out of the input once it is a theme's. +pub fn take_theme_paste(app: &mut SolveApp, ctx: &egui::Context) { + if !app.prefs_window.open || app.prefs_window.section != PAGE_INTERFACE { + return; + } + let Some(text) = ctx.input(|i| i.events.iter().find_map(|e| if let egui::Event::Paste(t) = e { Some(t.clone()) } else { None })) else { + return; + }; + if !looks_like_theme(&text) { + return; + } + ctx.input_mut(|i| { + i.events.retain(|e| { + !matches!(e, egui::Event::Paste(_) | egui::Event::Key { key: egui::Key::V, .. } | egui::Event::Key { key: egui::Key::Insert, .. }) + }) + }); + import_theme_text(app, Ok(text)); +} + +/// Files dropped on the theme Import tile are themes to import, not designs to open (#8226). +pub fn take_theme_drops(app: &mut SolveApp, ctx: &egui::Context) { + if !theme_drop_target(app, ctx) || !ctx.input(|i| !i.raw.dropped_files.is_empty()) { + return; + } + let files = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); + for f in files.iter().take(8) { + // The browser reads dropped files only asynchronously: the web shell takes them first and + // hands a theme's bytes to `import_theme_bytes` (#8226), so none reach this on wasm. + #[cfg(not(target_arch = "wasm32"))] + match f.bytes() { + Ok(bytes) => import_theme_bytes(app, bytes), + Err(e) => import_theme_text(app, Err(e.to_string())), + } + #[cfg(target_arch = "wasm32")] + let _ = f; + } +} + +/// Whether files dropped now land on the Import tile: the Preferences window is open and the +/// pointer was last seen over the tile. +pub fn theme_drop_target(app: &SolveApp, ctx: &egui::Context) -> bool { + app.prefs_window + .import_tile + .filter(|_| app.prefs_window.open) + .is_some_and(|rect| ctx.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p))) +} + +/// A file dropped on the Import tile, as bytes: imported when it is a theme, refused with the reason +/// otherwise. +pub fn import_theme_bytes(app: &mut SolveApp, bytes: Vec) { + let text = if bytes.len() > crate::theme_files::MAX_BYTES { + Err("the file is too large for a theme".to_string()) + } else { + String::from_utf8(bytes).map_err(|_| "not a theme file".to_string()) + }; + import_theme_text(app, text); +} + +pub fn import_theme(app: &mut SolveApp, v: &serde_json::Value) -> Result { + let theme = match v { + serde_json::Value::String(text) => crate::theme_files::parse(text)?, + other => crate::theme_files::from_value(other)?, + }; + let id = crate::theme_files::add(&mut app.preferences.custom_themes, theme)?; + select_theme(app, &id); + Ok(id) +} + +/// Remove an imported theme; when it is on, its base (dark or light) takes over. +fn remove_theme(app: &mut SolveApp, id: &str) -> Result<(), String> { + let Some(i) = app.preferences.custom_themes.iter().position(|t| t.id == id) else { + return Err(format!("no imported theme `{id}`")); + }; + let gone = app.preferences.custom_themes.remove(i); + if app.preferences.theme == id { + select_theme(app, if gone.base.is_dark() { "dark" } else { "light" }); + } + Ok(()) +} + +/// The theme on now as a complete theme file, a starting point for a new one. +fn current_theme_file(app: &SolveApp) -> serde_json::Value { + theme_file(app, &app.preferences.theme, app.ui.dark) +} + +/// Export the tile the user chose, without applying it or changing the dialog snapshot. +fn theme_file(app: &SolveApp, id: &str, system_dark: bool) -> serde_json::Value { + use crate::theme_files::{Base, export, find, resolve}; + match find(id, &app.preferences.custom_themes) { + Some(f) => export(&f.name, f.base, &resolve(f)), + None if id == "dark" || (id == "system" && system_dark) => export("Dark", Base::Dark, &crate::theme::Tokens::dark()), + None => export("Light", Base::Light, &crate::theme::Tokens::light()), + } +} + +/// Fold a setting an older release kept in its own field into the one this version reads. +/// `orbit_cursor` (`true` = the point under the cursor) became `orbit_around`. A 3D mouse +/// calibration that can't be used as it is (a hand edit) is dropped, so the device is read as it +/// reports rather than spinning the view. +pub fn migrate(mut p: Prefs) -> Prefs { + // Every saved file carries the old default limit; it reads as no limit. + if p.agent_chat_turn_limit == crate::agent_chat::gate::OLD_DEFAULT_TURN_LIMIT { + p.agent_chat_turn_limit = 0; + } + let valid_resource = |(kind, id): &(String, String)| !kind.is_empty() && kind.len() <= 64 && !id.is_empty() && id.len() <= 4096; + p.render_library_favorites = p.render_library_favorites.into_iter().filter(valid_resource).take(256).collect(); + p.render_library_recent = p.render_library_recent.into_iter().filter(valid_resource).take(32).collect(); + if !p.joint_rotation_coarse.is_finite() || !(0.001..=180.0).contains(&p.joint_rotation_coarse) { + p.joint_rotation_coarse = 10.0; + } + if !p.joint_rotation_fine.is_finite() || !(0.001..=180.0).contains(&p.joint_rotation_fine) { + p.joint_rotation_fine = 0.1; + } + if !accepted::wheel_zoom_speed(&p) { + p.wheel_zoom_speed = Prefs::default().wheel_zoom_speed; + } + if p.orbit_cursor { + p.orbit_around = OrbitAround::Cursor; + p.orbit_cursor = false; + } + if !crate::space_mouse::drives_each_once(p.space_mouse_axis_source) { + log::warn!("preferences: the 3D mouse axis assignment {:?} doesn't drive each axis once; using the default", p.space_mouse_axis_source); + p.space_mouse_axis_source = crate::space_mouse::SAME_AXES; + } + p.space_mouse_calibrations.retain(|device, calibration| { + let usable = calibration.is_usable(); + if !usable { + log::warn!("preferences: the 3D mouse calibration for `{device}` can't be used as it is; reading the device as it reports"); + } + usable + }); + p +} + +/// Drop plugin ids this page would not show, and keep at most [`crate::plugins::MAX_DISABLED`], +/// so a hand-edited preferences file cannot carry a huge or nonsense list. `set` still refuses +/// those instead of dropping them. +fn limit_disabled_plugins(mut p: Prefs) -> Prefs { + // The file size limits, likewise, are brought into range (#4086). + let limits = file_limits(&p); + let mb = solidcraft_engine::io::limits::MB; + (p.max_step_file_mb, p.max_design_file_mb) = + if solidcraft_engine::io::limits::ADJUSTABLE { (limits.step / mb, limits.design / mb) } else { (DEFAULT_STEP_MB, DEFAULT_DESIGN_MB) }; + p.disabled_plugins.retain(|id| crate::plugins::valid_id(id)); + if p.disabled_plugins.len() > crate::plugins::MAX_DISABLED { + p.disabled_plugins = p.disabled_plugins.into_iter().take(crate::plugins::MAX_DISABLED).collect(); + } + p +} + +/// Keep only known hidden tabs, each once, so a hand-edited preferences +/// file cannot carry a huge or nonsense list. `set` still refuses those instead of dropping them. +fn limit_toolbar_tabs(mut p: Prefs) -> Prefs { + fn known_once(list: Vec, allowed: &[&str]) -> Vec { + let mut kept: Vec = Vec::new(); + for tab in list { + if allowed.contains(&tab.as_str()) && !kept.contains(&tab) { + kept.push(tab); + } + } + kept + } + let allowed: Vec<&str> = crate::workspace::choosable_tabs().collect(); + p.hidden_toolbar_tabs = known_once(std::mem::take(&mut p.hidden_toolbar_tabs), &allowed); + p +} + +/// Saved preferences, keeping every one that still reads. A value this version doesn't +/// understand (a setting a newer or older release saved differently, a hand edit) falls back to +/// its default on its own instead of discarding all of them. +pub fn lenient(saved: &serde_json::Value) -> Prefs { + if let Ok(p) = serde_json::from_value::(saved.clone()) { + return limit_toolbar_tabs(limit_disabled_plugins(migrate(p))); + } + let Ok(mut cur) = serde_json::to_value(Prefs::default()) else { return Prefs::default() }; + if let (Some(o), Some(src)) = (cur.as_object_mut(), saved.as_object()) { + for (k, v) in src.iter().take(1000) { + // Keys this version doesn't have are ignored anyway. + let Some(old) = o.get(k).cloned() else { continue }; + o.insert(k.clone(), v.clone()); + if serde_json::from_value::(serde_json::Value::Object(o.clone())).is_err() { + log::warn!("preferences: `{k}` is not understood by this version; using its default"); + o.insert(k.clone(), old); + } + } + } + serde_json::from_value(cur).map(migrate).map(limit_disabled_plugins).map(limit_toolbar_tabs).unwrap_or_default() +} + +/// Set preferences from JSON (control channel); returns them all. +pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result { + for key in ["joint_rotation_coarse", "joint_rotation_fine"] { + if let Some(value) = p.get(key) + && value.as_f64().is_none_or(|v| !v.is_finite() || !(0.001..=180.0).contains(&v)) + { + return Err(format!("`{key}` must be 0.001…180 degrees")); + } + } + let mut cur = serde_json::to_value(&app.preferences).map_err(|e| e.to_string())?; + if let (Some(o), Some(src)) = (cur.as_object_mut(), p.as_object()) { + for (k, v) in src { + if !o.contains_key(k) { + return Err(format!("unknown preference `{k}`")); + } + o.insert(k.clone(), v.clone()); + } + } + // Saved preferences read an unknown mode as the default; asked for here, it is an error. + if let Some(v) = p.get("color_vision") + && v.as_str().and_then(crate::theme::ColorVision::from_id).is_none() + { + return Err("`color_vision` must be off, protan, deutan or tritan".into()); + } + if let Some(v) = p.get("viewport_theme") + && v.as_str().and_then(crate::theme::ViewportTheme::from_id).is_none() + { + return Err("`viewport_theme` must be theme, light or dark".into()); + } + if let Some(value) = p.get("navigation_bar") { + crate::navigation_bar::validate(value)?; + } + if let Some(v) = p.get("stand_up_unknown") + && !StandUpUnknown::ALL.iter().any(|c| v.as_str() == Some(c.id())) + { + return Err("`stand_up_unknown` must be ask, note or off".into()); + } + let new: Prefs = serde_json::from_value(cur).map_err(|e| e.to_string())?; + if !accepted::wheel_zoom_speed(&new) { + return Err("`wheel_zoom_speed` must be 0.25…4".into()); + } + let new = migrate(new); + if !UNITS.contains(&new.default_units.as_str()) { + return Err(format!("units must be one of {}", UNITS.join(", "))); + } + if !WINDOW_SYSTEMS.contains(&new.window_system.as_str()) { + return Err(format!("`window_system` must be one of {}", WINDOW_SYSTEMS.join(", "))); + } + if !NAV_PRESETS.iter().any(|p| p.id == new.nav) || !MSAA.contains(&new.msaa) { + return Err(format!("`nav` must be one of {} and `msaa` 1, 2, 4 or 8", NAV_PRESETS.iter().map(|p| p.id).collect::>().join(", "))); + } + if new.msaa != app.preferences.msaa && !app.msaa_supported.is_empty() && !app.msaa_supported.contains(&new.msaa) { + return Err(format!("this graphics device doesn't support `msaa` {}; it supports {:?}", new.msaa, app.msaa_supported)); + } + if new.graphics_adapter.len() > 1024 || new.graphics_adapter.chars().any(char::is_control) { + return Err("`graphics_adapter` must be a name of at most 1024 bytes without control characters".into()); + } + let file = crate::theme_files::find(&new.theme, &new.custom_themes); + if (!THEMES.iter().any(|(id, _)| *id == new.theme) && file.is_none()) || !["z", "y"].contains(&new.up_axis.as_str()) { + return Err("`theme` must be dark, light, system or a theme's id (see `theme_ids`) and `up_axis` z or y".into()); + } + if new.custom_themes.len() > crate::theme_files::MAX_CUSTOM || new.custom_themes.iter().any(|t| t.colors.len() > crate::theme_files::MAX_COLORS) { + return Err(format!("at most {} imported themes of {} colours each", crate::theme_files::MAX_CUSTOM, crate::theme_files::MAX_COLORS)); + } + for theme in &new.custom_themes { + theme.validate_radii()?; + crate::theme_files::parse_icon_palette(&theme.icon_palette)?; + crate::theme_files::parse_borders(&theme.borders)?; + } + if new.theme_follow != app.preferences.theme_follow { + if !FOLLOW_AVAILABLE && !new.theme_follow.trim().is_empty() { + return Err(FOLLOW_UNAVAILABLE.into()); + } + crate::theme_files::follow_path(&new.theme_follow)?; + } + if !crate::i18n::is_supported(&new.language) { + return Err(format!("`language` must be one of: {}", crate::i18n::LOCALES.iter().map(|locale| locale.id).collect::>().join(", "))); + } + if new.ui_font != app.preferences.ui_font && !new.ui_font.trim().is_empty() && crate::fonts::ui_font(&new.ui_font).is_none() { + return Err(format!("`ui_font`: `{}` is not an installed font family or a readable font file", new.ui_font.trim())); + } + if new.disabled_plugins.len() > crate::plugins::MAX_DISABLED || new.disabled_plugins.iter().any(|id| !crate::plugins::valid_id(id)) { + return Err(format!("`disabled_plugins` must be at most {} ids of lowercase letters, digits and hyphens", crate::plugins::MAX_DISABLED)); + } + if new.max_step_file_mb != app.preferences.max_step_file_mb || new.max_design_file_mb != app.preferences.max_design_file_mb { + let mb = solidcraft_engine::io::limits::MB; + let wanted = solidcraft_engine::io::limits::FileLimits { + step: new.max_step_file_mb.saturating_mul(mb), + design: new.max_design_file_mb.saturating_mul(mb), + }; + if !solidcraft_engine::io::limits::ADJUSTABLE && wanted != solidcraft_engine::io::limits::FileLimits::DEFAULT { + return Err("`max_step_file_mb` and `max_design_file_mb` can't change in the web app: a browser tab can't hold larger files".into()); + } + wanted.validate().map_err(|e| { + format!( + "`max_step_file_mb` must be {DEFAULT_STEP_MB}…{max} and `max_design_file_mb` {DEFAULT_DESIGN_MB}…{max}: {e}", + max = solidcraft_engine::io::limits::ceiling() / mb + ) + })?; + } + let once = |list: &[String], allowed: &[&str]| { + list.len() <= allowed.len() && list.iter().all(|tab| allowed.contains(&tab.as_str()) && list.iter().filter(|t| *t == tab).count() == 1) + }; + let allowed: Vec<&str> = crate::workspace::choosable_tabs().collect(); + if !once(&new.hidden_toolbar_tabs, &allowed) { + return Err(format!("`hidden_toolbar_tabs` lists toolbar tabs, each once: {}", allowed.join(", "))); + } + if !accepted::ui_scale(&new) || !accepted::look_at_speed(&new) { + return Err("`ui_scale` must be 0.5…2.5 and `look_at_speed` 0.25…4".into()); + } + if solidcraft_engine::doc::display_quality::DisplayQuality::parse(&new.display_quality).is_none() { + return Err("`display_quality` must be coarse, normal, fine or ultra".into()); + } + if !SUPERSAMPLING.contains(&new.supersampling) { + return Err("`supersampling` must be 1 (off), 1.5 or 2".into()); + } + if MiddleDoubleClick::parse(&new.middle_double_click).is_none() { + return Err("`middle_double_click` must be home, fit or off".into()); + } + if new.theme != app.preferences.theme && new.theme != "system" { + app.ui.dark = file.map_or(new.theme == "dark", |f| f.base.is_dark()); + } + let units_changed = new.default_units != app.preferences.default_units; + let up_changed = new.up_axis != app.preferences.up_axis; + let graphics_changed = new.msaa != app.preferences.msaa + || new.window_system != app.preferences.window_system + || new.graphics_adapter != app.preferences.graphics_adapter; + if p.get("layout").is_some() { + app.ui.layout = new.layout; + } + app.preferences = new; + apply_file_limits(&app.preferences); + if units_changed { + default_units_changed(app); + } + if graphics_changed { + save_graphics(app); + } + if up_changed { + up_axis_changed(app); + } + serde_json::to_value(&app.preferences).map_err(|e| e.to_string()) +} + +#[cfg(test)] +pub(crate) fn reveal_preference(h: &mut crate::scenario::Harness, handle: &str) { + // Interface includes the toolbar-tab choices as well as the existing font controls. + // Keep small scroll steps so a target cannot be skipped, with a bounded longer page. + for _ in 0..32 { + let page = crate::scenario::rect_of("dialog:page_body").expect("preference body"); + let visible = crate::scenario::rect_of(handle) + .map(|r| page.contains_rect(r)) + .unwrap_or_else(|| crate::scenario::handle_at(handle).is_some_and(|p| page.shrink(crate::theme::Tokens::get().space_16).contains(p))); + if visible { + return; + } + h.call("ui.scroll", json!({"x":page.center().x,"y":page.center().y,"delta":-100})); + h.frames(20); + } + panic!("preference {handle} was not revealed"); +} + +#[cfg(test)] +mod tests { + #[test] + fn cpu_progressive_policy_preferences_default_roundtrip_validate_and_reset_independently() { + let defaults = Prefs::default(); + assert!(defaults.render_cpu_progressive_every_pass && defaults.render_cpu_interactive_explicit_sampling); + let omitted: Prefs = serde_json::from_value(json!({})).unwrap(); + assert!(omitted.render_cpu_progressive_every_pass && omitted.render_cpu_interactive_explicit_sampling); + let mut app = SolveApp::new(Default::default(), Default::default()); + let document = app.session.doc.clone(); + let history = (app.session.revision, app.session.undo.len(), app.session.is_dirty()); + for key in ["render_cpu_progressive_every_pass", "render_cpu_interactive_explicit_sampling"] { + let reply = super::set(&mut app, &json!({key:false})).unwrap(); + assert_eq!(reply[key], false); + for invalid in [json!("false"), json!(0), json!(null), json!([])] { + assert!(super::set(&mut app, &json!({key:invalid})).is_err()); + assert_eq!(serde_json::to_value(&app.preferences).unwrap()[key], false); + } + } + let mut restored = SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&app.prefs()); + assert!(!restored.preferences.render_cpu_progressive_every_pass && !restored.preferences.render_cpu_interactive_explicit_sampling); + super::defaults(&mut restored, super::PAGE_GENERAL); + assert!(!restored.preferences.render_cpu_progressive_every_pass && !restored.preferences.render_cpu_interactive_explicit_sampling); + let reply = super::set(&mut restored, &json!({"render_cpu_progressive_every_pass":true})).unwrap(); + assert_eq!(reply["render_cpu_progressive_every_pass"], true); + assert_eq!(reply["render_cpu_interactive_explicit_sampling"], false); + super::defaults(&mut restored, super::PAGE_GRAPHICS); + assert!(restored.preferences.render_cpu_progressive_every_pass && restored.preferences.render_cpu_interactive_explicit_sampling); + assert!(std::sync::Arc::ptr_eq(&document, &app.session.doc)); + assert_eq!(history, (app.session.revision, app.session.undo.len(), app.session.is_dirty())); + } + + #[test] + fn render_open_result_on_start_defaults_persists_validates_and_resets() { + assert!(Prefs::default().render_open_result_on_start); + assert!(serde_json::from_value::(json!({})).unwrap().render_open_result_on_start); + let mut app = SolveApp::new(Default::default(), Default::default()); + let reply = super::set(&mut app, &json!({"render_open_result_on_start":false})).unwrap(); + assert_eq!(reply["render_open_result_on_start"], false); + for invalid in [json!("false"), json!(0), json!(null)] { + assert!(super::set(&mut app, &json!({"render_open_result_on_start":invalid})).is_err()); + assert!(!app.preferences.render_open_result_on_start); + } + let mut restored = SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&app.prefs()); + assert!(!restored.preferences.render_open_result_on_start); + super::defaults(&mut restored, super::PAGE_GRAPHICS); + assert!(restored.preferences.render_open_result_on_start); + } + + #[test] + fn trackpad_zoom_modifier_roundtrips_and_validates_control_values() { + assert_eq!(Prefs::default().trackpad_zoom_modifier, TrackpadZoomModifier::Off); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + for (id, value) in [ + ("cmd", TrackpadZoomModifier::Cmd), + ("alt", TrackpadZoomModifier::Alt), + ("ctrl", TrackpadZoomModifier::Ctrl), + ("off", TrackpadZoomModifier::Off), + ] { + set(&mut app, &json!({"trackpad_zoom_modifier": id})).unwrap(); + assert_eq!(app.preferences.trackpad_zoom_modifier, value); + let saved = serde_json::to_value(&app.preferences).unwrap(); + assert_eq!(saved["trackpad_zoom_modifier"], id); + assert_eq!(lenient(&saved).trackpad_zoom_modifier, value); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&app.prefs()); + assert_eq!(restored.preferences.trackpad_zoom_modifier, value); + } + for invalid in [json!("super"), json!(""), json!(42), json!(null)] { + assert!(set(&mut app, &json!({"trackpad_zoom_modifier": invalid})).is_err()); + assert_eq!(app.preferences.trackpad_zoom_modifier, TrackpadZoomModifier::Off); + assert_eq!(lenient(&json!({"trackpad_zoom_modifier": invalid})).trackpad_zoom_modifier, TrackpadZoomModifier::Off); + } + app.load_prefs(&json!({"preferences": {"trackpad_zoom_modifier": "future"}}).to_string()); + assert_eq!(app.preferences.trackpad_zoom_modifier, TrackpadZoomModifier::Off); + app.preferences.trackpad_zoom_modifier = TrackpadZoomModifier::Cmd; + reset_preferences(&mut app.preferences, PAGE_NAVIGATION); + assert_eq!(app.preferences.trackpad_zoom_modifier, TrackpadZoomModifier::Off); + } + + #[test] + fn navigation_bar_preferences_round_trip_and_recover_hostile_fields() { + use crate::navigation_bar::{Edge, Idle, Labels, NavigationBar, Position, Size}; + use serde_json::json; + assert_eq!(super::lenient(&json!({})).navigation_bar, NavigationBar::default()); + let p = super::lenient(&json!({"navigation_bar": { + "slots":["pan", "future_slot", "pan", "separator", "separator", "separator", "separator", "separator", 7, "fit"], + "position":"bottom_left", "edge":"top", "size":"regular", "labels":"labels", "idle":"hide" + }})); + assert_eq!(p.navigation_bar.slots, ["pan", "future_slot", "separator", "separator", "separator", "separator", "fit"]); + assert_eq!( + (p.navigation_bar.position, p.navigation_bar.edge, p.navigation_bar.size, p.navigation_bar.labels, p.navigation_bar.idle), + (Position::Left, Edge::Top, Size::Regular, Labels::Labels, Idle::Hide) + ); + let saved = serde_json::to_value(&p).unwrap(); + assert_eq!(serde_json::from_value::(saved).unwrap(), p); + for field in ["position", "edge", "size", "labels", "idle"] { + let mut value = serde_json::to_value(&p).unwrap(); + value["navigation_bar"][field] = json!({"wrong":"type"}); + let mut expected = p.clone(); + match field { + "position" => expected.navigation_bar.position = Position::default(), + "edge" => expected.navigation_bar.edge = Edge::default(), + "size" => expected.navigation_bar.size = Size::default(), + "labels" => expected.navigation_bar.labels = Labels::default(), + _ => expected.navigation_bar.idle = Idle::default(), + } + assert_eq!(super::lenient(&value), expected, "{field}"); + value["navigation_bar"][field] = json!("unknown"); + assert_eq!(super::lenient(&value), expected, "{field}"); + } + for value in [json!(null), json!(7), json!([]), json!({"slots":false})] { + assert_eq!(super::lenient(&json!({"navigation_bar":value})).navigation_bar, NavigationBar::default()); + } + let ids: Vec<_> = (0..100).map(|i| format!("future_{i}")).collect(); + let limited = super::lenient(&json!({"navigation_bar":{"slots":ids}})); + assert_eq!(limited.navigation_bar.slots.len(), crate::navigation_bar::MAX_SLOTS); + assert_eq!(limited.navigation_bar.slots.last().map(String::as_str), Some("future_15")); + let ids: Vec<_> = ["pan".to_owned(), "pan".to_owned()].into_iter().chain((0..20).map(|i| format!("future_{i}"))).collect(); + let limited = super::lenient(&json!({"navigation_bar":{"slots":ids}})); + assert_eq!(limited.navigation_bar.slots.len(), crate::navigation_bar::MAX_SLOTS); + assert_eq!(limited.navigation_bar.slots.last().map(String::as_str), Some("future_14")); + } + + #[test] + fn navigation_bar_control_reads_writes_validates_and_restores() { + use crate::navigation_bar::NavigationBar; + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + let initial = h.call("ui.prefs", json!({})); + assert_eq!(initial["result"]["navigation_bar"], serde_json::to_value(NavigationBar::default()).unwrap()); + let edit = json!({"navigation_bar":{"slots":["zoom", "future", "zoom", "display"], "position":"bottom_right", "size":"regular", "labels":"labels", "idle":"always"}}); + h.call("ui.prefs", json!({"open":"Interface"})); + let reply = h.call("ui.prefs", edit); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["navigation_bar"]["slots"], json!(["zoom", "future", "display"])); + let before = h.app.preferences.clone(); + for bad in [ + json!(null), + json!({"slots":"fit"}), + json!({"slots":[7]}), + json!({"position":"top"}), + json!({"size":true}), + json!({"labels":"text"}), + json!({"idle":10}), + json!({"unknown":true}), + ] { + assert!(super::control(&mut h.app, &json!({"navigation_bar":bad,"zoom_reverse":true})).is_err()); + assert_eq!(h.app.preferences, before, "failed updates are atomic"); + } + let mut restored = crate::SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.navigation_bar, before.navigation_bar); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.navigation_bar, NavigationBar::default()); + h.call("ui.prefs", json!({"open":"Interface","navigation_bar":{"slots":[]}})); + assert!(h.app.preferences.navigation_bar.slots.is_empty()); + h.call("ui.prefs", json!({"button":"defaults"})); + assert_eq!(h.app.preferences.navigation_bar, NavigationBar::default()); + } + + fn navbar_click(h: &mut crate::scenario::Harness, handle: &str) { + h.call("ui.prefs", json!({"open":"Interface/Navigation bar"})); + h.frames(20); + scroll_to_and_click(h, handle); + } + + #[test] + fn navigation_bar_editor_buttons_and_appearance_update_preferences() { + use crate::navigation_bar::{Idle, Labels, MenuDisplay, Position, Size}; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar", "navigation_bar":{"slots":["pan","fit","visual_style","display"]}})); + navbar_click(&mut h, "prefs:navbar:add:spin"); + assert_eq!(h.app.preferences.navigation_bar.slots, ["pan", "fit", "visual_style", "display", "spin"]); + navbar_click(&mut h, "prefs:navbar:slot:pan"); + navbar_click(&mut h, "prefs:navbar:right"); + assert_eq!(h.app.preferences.navigation_bar.slots, ["fit", "pan", "visual_style", "display", "spin"]); + navbar_click(&mut h, "prefs:navbar:remove"); + assert_eq!(h.app.preferences.navigation_bar.slots, ["fit", "visual_style", "display", "spin"]); + navbar_click(&mut h, "prefs:navbar:slot:visual_style"); + navbar_click(&mut h, "prefs:navbar:shows:0"); + assert_eq!(h.app.preferences.navigation_bar.menu_display("visual_style"), MenuDisplay::IconAndValue); + navbar_click(&mut h, "prefs:navbar:position:0"); + assert_eq!(h.app.preferences.navigation_bar.position, Position::Left); + navbar_click(&mut h, "prefs:navbar:position:2"); + assert_eq!(h.app.preferences.navigation_bar.position, Position::Right); + navbar_click(&mut h, "prefs:navbar:size:0"); + assert_eq!(h.app.preferences.navigation_bar.size, Size::Compact); + navbar_click(&mut h, "prefs:navbar:size:1"); + assert_eq!(h.app.preferences.navigation_bar.size, Size::Regular); + navbar_click(&mut h, "prefs:navbar:buttons:1"); + assert_eq!(h.app.preferences.navigation_bar.labels, Labels::Labels); + navbar_click(&mut h, "prefs:navbar:idle:0"); + assert_eq!(h.app.preferences.navigation_bar.idle, Idle::Always); + navbar_click(&mut h, "prefs:navbar:idle:2"); + assert_eq!(h.app.preferences.navigation_bar.idle, Idle::Hide); + let before = h.app.preferences.navigation_bar.clone(); + navbar_click(&mut h, "prefs:navbar:preview_as:1"); + assert_eq!(h.app.preferences.navigation_bar, before, "canvas preview is transient"); + navbar_click(&mut h, "prefs:navbar:show"); + assert!(!h.app.ui.show_navigation_bar); + navbar_click(&mut h, "prefs:navbar:show"); + assert!(h.app.ui.show_navigation_bar); + } + + #[test] + fn navigation_bar_appearance_segments_stay_inside_the_page_at_narrow_widths() { + for width in [1600, 880, 640, 600, 480] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":width,"height":1100})); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar", "navigation_bar":{"slots":["fit","visual_style","display","spin"]}})); + h.frames(20); + for (key, label, labels) in [ + ("position", "Position", &["Left", "Centre", "Right"][..]), + ("size", "Size", &["Compact", "Regular"][..]), + ("buttons", "Buttons", &["Icons", "Icons and labels"][..]), + ("idle", "When idle", &["Always visible", "Fade", "Hide until hovered"][..]), + ] { + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + let row = crate::scenario::rect_of(&format!("prefs:navbar:{key}")).unwrap(); + assert!(row.left() >= body.left() && row.right() <= body.right() + 0.5, "{key} at {width}: {row:?} outside {body:?}"); + assert_eq!(row.height(), crate::ui_kit::row_height(), "standard control height"); + let dropdown = crate::scenario::rect_of(&format!("dialog:segments:{label}")).is_none(); + if !dropdown { + let t = crate::theme::Tokens::get(); + let natural: f32 = labels + .iter() + .map(|option| { + h.ctx + .fonts_mut(|fonts| fonts.layout_no_wrap((*option).to_owned(), crate::fonts::semibold(t.font_label), t.form_ink)) + .size() + .x + .ceil() + + t.space_16 + }) + .sum(); + let control = crate::scenario::rect_of(&format!("dialog:control:{label}")).unwrap(); + assert!((row.width() - natural.min(control.width())).abs() < 0.5, "{key} hugs its content at {width}"); + } + if dropdown { + // Standard Segments fall back to the kit dropdown when their labels cannot fit. + navbar_click(&mut h, &format!("prefs:navbar:{key}")); + h.frames(2); + } + for (index, option) in labels.iter().enumerate() { + let cell = crate::scenario::rect_of(&format!("prefs:navbar:{key}:{index}")).unwrap(); + let at = crate::scenario::handle_at(&format!("prefs:navbar:{key}:{index}")).unwrap(); + assert!(cell.contains(at), "the scenario target is the actual choice"); + let mut text_found = false; + for shape in &h.shapes { + crate::test_support::each_shape(&shape.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape + && text.galley.job.text == *option + { + let bounds = text.galley.rect.translate(text.pos.to_vec2()); + if cell.contains(bounds.center()) { + assert!( + !text.galley.elided && cell.contains_rect(bounds), + "{key}:{index} text clips at {width}: {bounds:?} in {cell:?}" + ); + text_found = true; + } + } + }); + } + assert!(text_found, "{key}:{index} has painted, readable text at {width}"); + } + if dropdown { + h.step(&json!({"click":{"handle":format!("prefs:navbar:{key}:{}", labels.len() - 1)}})).unwrap(); + h.frames(2); + } + } + } + } + + #[test] + fn navigation_bar_inspector_header_reserves_one_line_for_actions() { + let t = crate::theme::Tokens::light(); + for width in [0.0, 80.0, 200.0, 520.0, 640.0, 760.0, 880.0] { + for remove_width in [75.0, 160.0] { + let bounds = egui::Rect::from_min_size(egui::pos2(10.0, 20.0), egui::vec2(width, t.control_height)); + let (name, buttons, compact) = super::navbar::inspector_header_layout(bounds, remove_width, &t); + assert!(bounds.contains_rect(name)); + for rect in buttons { + assert!(bounds.contains_rect(rect), "{width}: {rect:?} outside {bounds:?}"); + assert_eq!(rect.top(), bounds.top()); + assert_eq!(rect.bottom(), bounds.bottom()); + assert!(name.right() <= rect.left()); + } + assert!((buttons.last().unwrap().right() - bounds.right()).abs() < 0.01); + for pair in buttons.windows(2) { + assert!(pair[0].right() <= pair[1].left()); + } + if width >= 760.0 { + assert!(!compact, "wide rows keep Remove's label"); + } else if width <= 80.0 { + assert!(compact, "narrow rows keep Remove as an icon"); + } + if !compact { + assert_eq!(buttons[0].width(), t.control_height, "Move left is always icon-only"); + assert_eq!(buttons[1].width(), t.control_height, "Move right is always icon-only"); + assert_eq!(buttons[2].width(), remove_width); + } + } + } + } + + #[test] + fn navigation_bar_inspector_and_status_keep_full_width_for_every_selection() { + for width in [480, 600, 880, 1030, 1200, 1600] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":width,"height":1100})); + h.call( + "ui.prefs", + json!({"open":"Interface/Navigation bar", "navigation_bar":{"slots":["pan","fit","visual_style","display","separator"]}}), + ); + h.frames(20); + for slot in [None, Some("pan"), Some("fit"), Some("visual_style"), Some("display"), Some("separator")] { + if let Some(slot) = slot { + navbar_click(&mut h, &format!("prefs:navbar:slot:{slot}")); + h.frames(3); + } + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + let card = crate::scenario::rect_of("prefs:navbar:inspector").unwrap(); + assert!( + (card.left() - body.left()).abs() < 0.5 && (card.right() - body.right()).abs() < 0.5, + "{slot:?} at {width}: {card:?} vs {body:?}" + ); + let status = crate::scenario::rect_of("prefs:navbar:status").unwrap(); + let reset = crate::scenario::rect_of("prefs:navbar:reset").unwrap(); + let show = crate::scenario::rect_of("prefs:navbar:show").unwrap(); + assert_eq!(status.right(), body.right()); + assert!(status.contains_rect(reset) && status.contains_rect(show)); + assert!(show.right() <= reset.left()); + assert_eq!(reset.center().y, show.center().y); + if slot.is_some() { + let header = crate::scenario::rect_of("prefs:navbar:inspector:header").unwrap(); + let name = crate::scenario::rect_of("prefs:navbar:inspector:name").unwrap(); + let actions: Vec<_> = + ["left", "right", "remove"].iter().map(|key| crate::scenario::rect_of(&format!("prefs:navbar:{key}")).unwrap()).collect(); + for rect in &actions { + assert!(header.contains_rect(*rect), "{slot:?} at {width}: {rect:?} outside {header:?}"); + assert_eq!(rect.center().y, header.center().y); + assert!(name.right() <= rect.left()); + } + assert_eq!(actions[0].width(), header.height(), "Move left stays icon-only"); + assert_eq!(actions[1].width(), header.height(), "Move right stays icon-only"); + assert_eq!(actions.last().unwrap().right(), header.right()); + } + for (_, at) in crate::scenario::handles("prefs:navbar:add:") { + assert!(at.x >= body.left() && at.x <= body.right(), "tray actions stay in their tiles"); + } + } + } + } + + #[test] + fn interface_sections_share_the_page_content_width_before_and_after_navigation() { + for width in [600, 880, 1030, 1200, 1496, 1600] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":width,"height":1100})); + h.call("ui.prefs", json!({"open":"Interface"})); + h.frames(20); + for _ in 0..2 { + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + let window = crate::scenario::rect_of("prefs:window").unwrap(); + let t = crate::theme::Tokens::get(); + let inset = t.space_16 + t.space_4 + crate::ui_kit::navigation_popup_frame().stroke.width; + assert!((body.right() - (window.right() - inset)).abs() < 0.5, "{width}: page {body:?} leaves unused window content {window:?}"); + for key in ["theme", "layout", "navigation_bar", "scale", "colour_vision"] { + let section = crate::scenario::rect_of(&format!("prefs:section:{key}")).unwrap(); + assert!( + (section.left() - body.left()).abs() < 0.5 && (section.right() - body.right()).abs() < 0.5, + "{key} at {width}: {section:?} vs {body:?}" + ); + } + for key in ["prefs:navbar:stage", "dialog:divider:scale_font", "dialog:row:Font"] { + let row = crate::scenario::rect_of(key).unwrap(); + assert!((row.right() - body.right()).abs() < 0.5, "{key} at {width}: {row:?} vs {body:?}"); + } + h.call("ui.scroll", json!({"x":body.center().x,"y":body.center().y,"delta":-600})); + h.frames(20); + } + } + } + + #[test] + fn navigation_bar_preview_stage_follows_position_live() { + use crate::navigation_bar::Position; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar","navigation_bar":{"slots":["pan","fit","display"]}})); + for (index, position) in [(0, Position::Left), (1, Position::Centre), (2, Position::Right)] { + navbar_click(&mut h, &format!("prefs:navbar:position:{index}")); + h.frames(3); + let stage = crate::scenario::rect_of("prefs:navbar:stage").unwrap(); + let bar = crate::scenario::rect_of("prefs:navbar:bar").unwrap(); + assert_eq!(h.app.preferences.navigation_bar.position, position); + assert_eq!(stage.height(), crate::ui_kit::NAV_STAGE_HEIGHT); + assert_eq!(bar.center().y, stage.center().y); + match position { + Position::Left => assert_eq!(bar.left(), stage.left() + crate::ui_kit::NAV_BORDER + crate::ui_kit::NAV_STAGE_INSET), + Position::Centre => assert_eq!(bar.center().x, stage.center().x), + Position::Right => assert_eq!(bar.right(), stage.right() - crate::ui_kit::NAV_BORDER - crate::ui_kit::NAV_STAGE_INSET), + } + } + } + + #[test] + fn navigation_bar_editor_drag_adds_reorders_and_removes() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar", "navigation_bar":{"slots":["pan","fit","display"]}})); + h.frames(20); + let preview = crate::scenario::rect_of("prefs:navbar:preview").unwrap(); + h.step(&json!({"drag":[{"handle":"prefs:navbar:tile:spin"}, [preview.right()-8.0,preview.center().y]],"steps":12})).unwrap(); + h.frames(4); + assert_eq!(h.app.preferences.navigation_bar.slots, ["pan", "fit", "display", "spin"]); + let pan = crate::scenario::rect_of("prefs:navbar:slot:pan").unwrap(); + h.step(&json!({"drag":[{"handle":"prefs:navbar:slot:spin"}, [pan.left()+1.0,pan.center().y]],"steps":12})).unwrap(); + h.frames(4); + assert_eq!(h.app.preferences.navigation_bar.slots, ["spin", "pan", "fit", "display"]); + let preview = crate::scenario::rect_of("prefs:navbar:preview").unwrap(); + h.step(&json!({"drag":[{"handle":"prefs:navbar:slot:spin"}, [preview.center().x,preview.bottom()+80.0]],"steps":12})).unwrap(); + h.frames(4); + assert_eq!(h.app.preferences.navigation_bar.slots, ["pan", "fit", "display"]); + // Empty stage space is off the bar too; it must remove rather than append a moved slot. + h.step(&json!({"drag":[{"handle":"prefs:navbar:slot:pan"}, [preview.right()-4.0,preview.center().y]],"steps":12})).unwrap(); + h.frames(4); + assert_eq!(h.app.preferences.navigation_bar.slots, ["fit", "display"]); + } + + #[test] + fn navigation_bar_menu_options_cancel_defaults_and_section_reset() { + use crate::navigation_bar::NavigationBar; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let before = h.app.preferences.navigation_bar.clone(); + let options = json!({"slots":["visual_style","pan"],"slot_options":{"visual_style":{"shows":"icon_and_value"}},"size":"regular"}); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar","navigation_bar":options})); + h.app.run("view.navigation_bar", json!({"visible":false})).unwrap(); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.navigation_bar, before); + assert!(h.app.ui.show_navigation_bar); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar","navigation_bar":options})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert_eq!(h.app.preferences.navigation_bar, NavigationBar::default()); + h.call("ui.prefs", json!({"navigation_bar":options})); + navbar_click(&mut h, "prefs:navbar:reset"); + assert_eq!(h.app.preferences.navigation_bar, NavigationBar::default()); + navbar_click(&mut h, "dialog:section:Navigation bar"); + assert!(crate::scenario::handle_at("prefs:navbar:slot:pan").is_none(), "the section collapsed"); + h.call("ui.prefs", json!({"open":"Interface/Navigation bar"})); + h.frames(20); + let preview = crate::scenario::rect_of("prefs:navbar:preview").unwrap(); + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + assert!(body.contains(preview.center()), "the route reopens and scrolls to the section"); + } + + #[test] + fn the_ghost_position_defaults_round_trips_and_reads_tolerantly() { + use super::SpaceMouseGhost::{LeftViewport as Current, LeftWindow as Left, RightViewport as Right}; + assert_eq!(serde_json::from_value::(serde_json::json!({})).unwrap().space_mouse_ghost_position, Current); + for position in [Current, Left, Right] { + let prefs = super::Prefs { space_mouse_ghost_position: position, ..Default::default() }; + let again: super::Prefs = serde_json::from_value(serde_json::to_value(&prefs).unwrap()).unwrap(); + assert_eq!(again.space_mouse_ghost_position, position); + } + // A value from a newer build costs that setting only. + for (old, position) in [("current", Current), ("left", Left), ("right", Right)] { + let read = serde_json::from_value::(serde_json::json!({ "space_mouse_ghost_position": old })).unwrap(); + assert_eq!(read.space_mouse_ghost_position, position, "{old}"); + } + assert_eq!(serde_json::to_value(Left).unwrap(), "left_window"); + let read = super::lenient(&serde_json::json!({ "space_mouse_ghost_position": "top", "space_mouse_speed": 2.0 })); + assert_eq!((read.space_mouse_ghost_position, read.space_mouse_speed), (Current, 2.0)); + } + + #[test] + fn the_calibration_offer_record_round_trips_and_reads_tolerantly() { + let prefs: super::Prefs = + serde_json::from_value(serde_json::json!({ "space_mouse_offered": ["spacenavd", 7, null, "hid 046d:c62b"] })).unwrap(); + assert_eq!(prefs.space_mouse_offered, ["spacenavd".to_string(), "hid 046d:c62b".to_string()].into()); + let again: super::Prefs = serde_json::from_value(serde_json::to_value(&prefs).unwrap()).unwrap(); + assert_eq!(again.space_mouse_offered, prefs.space_mouse_offered); + // Files from before it existed read as nothing offered yet. + assert!(serde_json::from_value::(serde_json::json!({})).unwrap().space_mouse_offered.is_empty()); + } + + /// The 3D mouse section is laid out inside the panel it is in, at every panel width: nothing it + /// draws reaches past the right edge (the rows used to run off it and get clipped). + #[test] + fn the_3d_mouse_section_stays_inside_the_panel_at_every_width() { + for width in [420.0_f32, 560.0, 700.0, 900.0, 1200.0] { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.space_mouse.device = Some("hid 046d:c62b".into()); + app.space_mouse.drivers = Some(crate::space_mouse::DriversPresent { spacenavd: true, direct: true, denied: false }); + app.preferences.space_mouse_in_view = true; + // Calibrated, so the device's picture and the test model sit side by side where there is room. + let axes = std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { + source, + reversed: false, + rest: 0, + dead_zone: 0, + full: [350; 2], + }); + app.preferences.space_mouse_calibrations.insert( + "hid 046d:c62b".into(), + solidcraft_space_mouse::Calibration { dead_zone_share: 0.0, kind: solidcraft_space_mouse::Kind::ReturnToCenter, axes }, + ); + let ctx = crate::fonts::test_context(); + let panel = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(width, 1400.0)); + for frame in 0..4 { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width + 40.0, 1500.0))), + focused: true, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| { + ui.scope_builder(egui::UiBuilder::new().max_rect(panel), |ui| { + super::space_mouse_section(&mut app, ui); + let wide: Vec<_> = crate::scenario::rects("").into_iter().filter(|(_, r)| r.right() > panel.right() + 0.5).collect(); + assert!( + ui.min_rect().right() <= panel.right() + 0.5, + "width {width}, frame {frame}: the section reaches {}; past the panel: {wide:?}", + ui.min_rect().right() + ); + }); + }); + output.textures_delta.clear(); + } + } + } + + /// The calibration window keeps its texts and sliders inside itself at the widths it can be + /// given, for both kinds of device (the notice card is clamped to the free width by construction). + #[test] + fn the_calibration_window_keeps_its_contents_inside() { + for width in [360.0_f32, 520.0, 900.0] { + for kind in [solidcraft_space_mouse::Kind::ReturnToCenter, solidcraft_space_mouse::Kind::Trackball] { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.space_mouse.device = Some("hid 046d:c62b".into()); + crate::space_mouse_calibration::start(&mut app); + app.space_mouse.calibrating.as_mut().unwrap().1.choose(kind); + let ctx = crate::fonts::test_context(); + for _ in 0..6 { + crate::scenario::clear_handles(); + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 900.0))), + focused: true, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| crate::space_mouse_calibration::show(&mut app, ui.ctx())); + output.textures_delta.clear(); + } + let window = crate::scenario::rect_of("dialog:window").expect("the window is drawn"); + for (name, rect) in crate::scenario::rects("dialog:").into_iter().filter(|(name, _)| { + name.starts_with("dialog:slider") + || name.starts_with("dialog:widget") + || name.starts_with("dialog:note") + || name.starts_with("dialog:report") + }) { + assert!( + rect.right() <= window.right() + 0.5 && rect.left() >= window.left() - 0.5, + "width {width} {kind:?}: {name} {rect:?} is outside {window:?}" + ); + } + } + } + } + + #[test] + fn preferred_units_update_only_a_blank_unsaved_design() { + for design in ["new", "saved", "content"] { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + match design { + "saved" => app.session.path = Some("empty.solidcraft".into()), + "content" => { + app.session.execute("sketch.create", &serde_json::json!({"plane": "XY"})).unwrap(); + app.session.mark_saved(); + } + _ => {} + } + let dirty = app.session.is_dirty(); + let undo = app.session.undo.len(); + super::set(&mut app, &serde_json::json!({"default_units": "in"})).unwrap(); + assert_eq!(app.preferences.default_units, "in"); + assert_eq!(app.session.doc.units, if design == "new" { "in" } else { "mm" }, "{design}"); + assert_eq!(app.session.is_dirty(), dirty, "{design}"); + assert_eq!(app.session.undo.len(), undo, "{design}"); + if design == "new" { + super::control(&mut app, &serde_json::json!({"open": "Design"})).unwrap(); + super::set(&mut app, &serde_json::json!({"default_units": "ft"})).unwrap(); + assert_eq!(app.session.doc.units, "ft"); + super::control(&mut app, &serde_json::json!({"button": "cancel"})).unwrap(); + assert_eq!(app.session.doc.units, "in"); + super::defaults(&mut app, super::PAGE_DESIGN); + assert_eq!(app.session.doc.units, "mm"); + assert!(!app.session.is_dirty()); + assert!(app.session.undo.is_empty()); + } + } + } + + /// What Preferences says of the 3D mouse before one is confirmed: a reachable reader that has sent + /// nothing yet asks for a movement; only nothing reachable says none was found. + #[test] + fn the_device_line_asks_for_a_movement_when_a_reader_is_reachable_and_only_then_says_none_found() { + use crate::space_mouse::DriversPresent; + let none = DriversPresent { spacenavd: false, direct: false, denied: false }; + assert!(!waiting_for_a_record(None) && !waiting_for_a_record(Some(none))); + assert!(waiting_for_a_record(Some(DriversPresent { spacenavd: true, direct: false, denied: false })), "a daemon, no record yet"); + assert!(waiting_for_a_record(Some(DriversPresent { spacenavd: false, direct: true, denied: false })), "a readable device, no record yet"); + assert!(waiting_for_a_record(Some(DriversPresent { spacenavd: true, direct: true, denied: false }))); + // The texts differ, and the first one is the Calibrate hint. + assert_ne!(crate::i18n::tr("ui.3d_mouse_none"), crate::i18n::tr("ui.3d_mouse_calibrate_wait")); + // A confirmed device is neither (the status names it). + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.space_mouse.device = Some("spacenavd".into()); + h.app.space_mouse.drivers = Some(DriversPresent { spacenavd: true, direct: false, denied: false }); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(3); + assert!(h.app.prefs_window.open); + } + + /// Calibration starts while Preferences is open, and its window is on top of it; with no device + /// known there is nothing to start (the button is off and says why, see the hint key). + #[test] + fn calibration_opens_over_an_open_preferences_and_waits_for_a_device() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + // After a driver change and before any reading: no device, so nothing starts. + h.app.space_mouse.device = None; + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(5); + assert!(crate::i18n::tr("ui.3d_mouse_calibrate_wait").starts_with("Move the 3D mouse")); + crate::space_mouse_calibration::start(&mut h.app); + h.frames(3); + assert!(h.app.space_mouse.calibrating.is_none() && h.app.prefs_window.open); + // The device is seen: the window opens, above Preferences, which stays open. + h.app.space_mouse.device = Some("hid 046d:c62b".into()); + h.frames(3); + crate::space_mouse_calibration::start(&mut h.app); + h.frames(5); + assert!(h.app.space_mouse.calibrating.is_some() && h.app.prefs_window.open); + let window = crate::scenario::rect_of("dialog:window").expect("the calibration window is the last window drawn"); + let top = h.ctx.layer_id_at(window.center()); + assert!(top.is_some_and(|layer| layer.id == egui::Id::new("sc_space_mouse_calibration")), "top is {top:?}"); + } + + /// Scrolls vertically to the handle, then clicks after the wheel animation settles. + /// Edge-aligned controls are valid targets; scrolling cannot move them inward horizontally. + fn scroll_to_and_click(h: &mut crate::scenario::Harness, handle: &str) { + for _ in 0..60 { + let body = crate::scenario::rect_of("prefs:page_body").expect("the page body"); + let target = crate::scenario::handle_at(handle); + if let Some(at) = target + && body.contains(at) + { + // The wheel scrolls smoothly: let it come to rest, then click where the handle is now. + h.frames(20); + let at = crate::scenario::handle_at(handle).unwrap_or(at); + if body.contains(egui::pos2(at.x, at.y)) { + h.step(&serde_json::json!({"click": {"handle": handle}})).unwrap(); + h.frames(5); + return; + } + } + h.app.synthetic.push(egui::Event::PointerMoved(body.center())); + h.app.synthetic.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, if target.is_some_and(|at| at.y < body.top()) { 60.0 } else { -60.0 }), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }); + h.frames(2); + } + panic!("{handle} never came into view"); + } + + /// The page's rows share one label column, widened by the longest label in the form. The 3D + /// mouse section brought longer labels, which moved every control (Orbit around's among them) to + /// the right and turned its three buttons into a dropdown. Measured: each row's control left edge and + /// width with the section open and folded, at the window sizes the app is used at. + #[test] + fn folding_the_3d_mouse_section_does_not_move_the_controls_of_the_rows_above_it() { + let mut report = Vec::new(); + for width in [900, 1100, 1318, 1600, 1920] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.space_mouse.device = Some("hid 046d:c62b".into()); + h.call("ui.resize", serde_json::json!({"width": width, "height": 900})); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(6); + let rows = ["Orbit around", "Middle double-click", "View navigator"]; + let control = |name: &str| crate::scenario::rect_of(&format!("dialog:control:{name}")).map(|r| (r.left(), r.width())); + let buttons = || crate::scenario::rect_of("dialog:segments:Orbit around").is_some(); + let (open, open_form) = (rows.map(control), buttons()); + scroll_to_and_click(&mut h, "dialog:section:3D mouse"); + // Back to the top, where the rows above are on screen again. + h.app.synthetic.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 5000.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }); + h.frames(6); + let (folded, folded_form) = (rows.map(control), buttons()); + eprintln!("window {width}: open {open:?} buttons {open_form}; folded {folded:?} buttons {folded_form}"); + if folded != open || folded_form != open_form { + report.push(format!("window {width}: open {open:?} buttons {open_form}, folded {folded:?} buttons {folded_form}")); + } + } + assert!(report.is_empty(), "{}", report.join("\n")); + } + + /// The meter in a view axis row shows the motion chosen in its "driven by" menu, calibrated or not. + #[test] + fn an_axis_meter_follows_the_motion_that_drives_it() { + let raw = [0, 0, 0, 175, 0, 0]; + let full = f32::from(crate::space_mouse::FULL_SCALE); + let mut source = crate::space_mouse::SAME_AXES; + assert_eq!(axis_meter(None, raw, source, 2).0, 0.0, "Zoom reads its own motion"); + crate::space_mouse::reassign(&mut source, 2, 3); + assert_eq!(axis_meter(None, raw, source, 2), (175.0 / full, [0.0; 2]), "Zoom now shows Rotation X"); + assert_eq!(axis_meter(None, raw, source, 3).0, 0.0, "and the row that gave Rotation X up shows what it took in exchange"); + let axes = + std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { source, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }); + let calibration = solidcraft_space_mouse::Calibration { dead_zone_share: 0.2, kind: solidcraft_space_mouse::Kind::ReturnToCenter, axes }; + assert_eq!(axis_meter(Some(&calibration), raw, source, 2), (0.5, [0.2; 2]), "calibrated: share of travel, with the dead zone"); + } + + /// Restore defaults for the 3D mouse section puts back what it lists, and nothing else. + #[test] + fn restoring_the_3d_mouse_section_resets_its_settings_and_keeps_the_rest() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let axes = + std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { source, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }); + let calibration = solidcraft_space_mouse::Calibration { dead_zone_share: 0.2, kind: solidcraft_space_mouse::Kind::ReturnToCenter, axes }; + let p = &mut h.app.preferences; + p.space_mouse_calibrations.insert("hid 046d:c62b".into(), calibration); + p.space_mouse_buttons.insert("hid 046d:c62b".into(), [(1, crate::space_mouse::ButtonJob::Settings)].into()); + p.space_mouse_offered.insert("hid 046d:c62b".into()); + p.space_mouse_offer_never = true; + p.space_mouse_enabled = false; + p.space_mouse_driver = SpaceMouseDriver::Direct; + p.space_mouse_speed = 2.5; + p.space_mouse_reverse = [true; 6]; + p.space_mouse_axis_speed = [0.25; 6]; + p.space_mouse_axis_source = [1, 0, 2, 3, 4, 5]; + p.space_mouse_ghost_position = SpaceMouseGhost::LeftWindow; + p.space_mouse_in_view = true; + let before = h.app.preferences.clone(); + let camera = h.app.cam; + restore_space_mouse_defaults(&mut h.app); + let d = Prefs::default(); + let p = &h.app.preferences; + assert_eq!( + (p.space_mouse_driver, p.space_mouse_speed, p.space_mouse_reverse), + (d.space_mouse_driver, d.space_mouse_speed, d.space_mouse_reverse) + ); + assert_eq!((p.space_mouse_axis_speed, p.space_mouse_axis_source), (d.space_mouse_axis_speed, d.space_mouse_axis_source)); + assert_eq!((p.space_mouse_ghost_position, p.space_mouse_in_view), (d.space_mouse_ghost_position, d.space_mouse_in_view)); + // Kept: the calibration (dead zone too), the buttons, the offered set, never, enabled, the rest of the page. + assert_eq!(p.space_mouse_calibrations, before.space_mouse_calibrations); + assert_eq!(p.space_mouse_buttons, before.space_mouse_buttons); + assert_eq!(p.space_mouse_offered, before.space_mouse_offered); + assert!(p.space_mouse_offer_never && !p.space_mouse_enabled); + assert_eq!(p.nav, before.nav); + assert_eq!(h.app.cam, camera); + // And it asks first: the real button only arms it (see cancelling_the_restore_question_changes_nothing). + assert!(!h.app.space_mouse.restore_pending); + } + + /// Opens Preferences on the Navigation page with the 3D mouse section open and these settings + /// changed from their defaults, as a person who changed them would find it. + fn changed_3d_mouse_settings(device: Option<&str>) -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.space_mouse.device = device.map(str::to_owned); + let axes = + std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { source, reversed: false, rest: 0, dead_zone: 0, full: [350; 2] }); + let calibration = solidcraft_space_mouse::Calibration { dead_zone_share: 0.2, kind: solidcraft_space_mouse::Kind::ReturnToCenter, axes }; + let p = &mut h.app.preferences; + p.space_mouse_calibrations.insert("hid 046d:c62b".into(), calibration); + p.space_mouse_driver = SpaceMouseDriver::Direct; + p.space_mouse_speed = 2.5; + p.space_mouse_reverse = [true; 6]; + p.space_mouse_axis_speed = [0.25; 6]; + p.space_mouse_axis_source = [1, 0, 2, 3, 4, 5]; + p.space_mouse_ghost_position = SpaceMouseGhost::LeftWindow; + p.space_mouse_in_view = true; + h.call("ui.resize", serde_json::json!({"width": 1600, "height": 4000})); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(36); + open_advanced(&mut h); + h + } + + /// Opens the section's "Advanced" disclosure, which starts closed. Once per harness: it toggles. + fn open_advanced(h: &mut crate::scenario::Harness) { + scroll_to_and_click(h, "dialog:section:Advanced"); + h.frames(10); + } + + /// The driver, dead zone, axis table and buttons are rarely needed, so they start folded away and + /// are not drawn until the reader opens "Advanced"; the everyday controls are there either way. + #[test] + fn the_advanced_3d_mouse_settings_start_folded_away() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.space_mouse.device = Some("hid 046d:c62b".into()); + h.app.space_mouse.drivers = Some(crate::space_mouse::DriversPresent { spacenavd: true, direct: true, denied: false }); + h.call("ui.resize", serde_json::json!({"width": 1600, "height": 4000})); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(36); + let drawn = |name: &str| crate::scenario::rect_of(&format!("dialog:row:{name}")).is_some(); + let (driver, axes) = (crate::i18n::tr("ui.3d_mouse_driver"), crate::i18n::tr("ui.3d_mouse_button").replace("{number}", "1")); + assert!(drawn("Calibration") && drawn("Overall speed"), "everyday controls are always there"); + assert!(!drawn(driver) && !drawn(&axes), "closed: no driver row, no buttons"); + assert!(crate::scenario::rect_of("dialog:section:Advanced").is_some()); + open_advanced(&mut h); + assert!(drawn(driver), "open: the driver row"); + assert!(crate::scenario::rect_of("dialog:button::Restore defaults").is_some(), "open: the restore button"); + open_advanced(&mut h); + assert!(!drawn(driver), "closed again"); + } + + /// The question is short, says what stays, and exists in every language. + #[test] + fn the_restore_question_is_short_and_says_what_stays() { + let english = crate::i18n::tr("ui.3d_mouse_restore_ask"); + assert_eq!(english, "Set the 3D mouse settings back to their defaults? Your calibration and button mapping stay."); + for catalog in crate::i18n::LOCALES { + let text = crate::i18n::Locale::for_language(catalog.id).text("ui.3d_mouse_restore_ask"); + assert!(text.chars().count() > 20 && text.chars().count() < 140 && text != "ui.3d_mouse_restore_ask", "{}", catalog.id); + } + } + + /// Cancel on the question leaves every setting as it was, and the question goes away. + #[test] + fn cancelling_the_restore_question_changes_nothing() { + let mut h = changed_3d_mouse_settings(Some("hid 046d:c62b")); + let before = h.app.preferences.clone(); + scroll_to_and_click(&mut h, "dialog:button::Restore defaults"); + assert!(h.app.space_mouse.restore_pending, "the first click only asks"); + assert_eq!(h.app.preferences, before, "asking changes nothing"); + scroll_to_and_click(&mut h, "dialog:button::Cancel"); + assert!(!h.app.space_mouse.restore_pending); + assert_eq!(h.app.preferences, before); + } + + /// Accepting works with no device connected, and a device connecting afterwards does not bring the + /// old values back (nothing is kept apart from the preferences, and the calibration stays). + #[test] + fn restoring_with_no_device_works_and_a_later_connection_brings_nothing_back() { + let mut h = changed_3d_mouse_settings(None); + let calibrations = h.app.preferences.space_mouse_calibrations.clone(); + scroll_to_and_click(&mut h, "dialog:button::Restore defaults"); + scroll_to_and_click(&mut h, "dialog:button::Restore defaults"); + assert!(!h.app.space_mouse.restore_pending); + let d = Prefs::default(); + let restored = |h: &crate::scenario::Harness| { + let p = &h.app.preferences; + (p.space_mouse_driver, p.space_mouse_speed, p.space_mouse_reverse, p.space_mouse_axis_speed, p.space_mouse_axis_source) + == (d.space_mouse_driver, d.space_mouse_speed, d.space_mouse_reverse, d.space_mouse_axis_speed, d.space_mouse_axis_source) + && (p.space_mouse_ghost_position, p.space_mouse_in_view) == (d.space_mouse_ghost_position, d.space_mouse_in_view) + }; + assert!(restored(&h), "restored with the device away"); + // The device connects (and its calibration applies): the defaults stay. + h.app.space_mouse.device = Some("hid 046d:c62b".into()); + h.frames(30); + assert!(restored(&h), "still the defaults after the device connected"); + assert_eq!(h.app.preferences.space_mouse_calibrations, calibrations, "its calibration is kept"); + } + + /// What a restore sets, and what the prefs file holds of it. + fn section_is_at_defaults(app: &SolveApp) -> bool { + let (p, d) = (&app.preferences, Prefs::default()); + (p.space_mouse_driver, p.space_mouse_speed, p.space_mouse_reverse, p.space_mouse_axis_speed, p.space_mouse_axis_source) + == (d.space_mouse_driver, d.space_mouse_speed, d.space_mouse_reverse, d.space_mouse_axis_speed, d.space_mouse_axis_source) + && (p.space_mouse_ghost_position, p.space_mouse_in_view) == (d.space_mouse_ghost_position, d.space_mouse_in_view) + } + + /// Restore, then closing the dialog with its own Cancel while the question is up: the question is not + /// still asked when the dialog opens again, and nothing was changed. + #[test] + fn closing_preferences_with_the_restore_question_up_does_not_leave_it_armed() { + let mut h = changed_3d_mouse_settings(Some("hid 046d:c62b")); + let before = h.app.preferences.clone(); + scroll_to_and_click(&mut h, "dialog:button::Restore defaults"); + assert!(h.app.space_mouse.restore_pending); + h.step(&serde_json::json!({"click": {"handle": "dialog:cancel"}})).unwrap(); + h.frames(6); + assert!(!h.app.prefs_window.open, "the dialog closed"); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(6); + assert!(!h.app.space_mouse.restore_pending, "the question is not asked again on its own"); + assert_eq!(h.app.preferences, before); + } + + /// Confirming with the real buttons is what the prefs file holds afterwards: a new run that loads it + /// has the defaults for the section and the calibration still there. + #[test] + fn a_confirmed_restore_is_what_the_next_run_loads() { + let mut h = changed_3d_mouse_settings(Some("hid 046d:c62b")); + let calibrations = h.app.preferences.space_mouse_calibrations.clone(); + assert!(!section_is_at_defaults(&h.app)); + scroll_to_and_click(&mut h, "dialog:button::Restore defaults"); + scroll_to_and_click(&mut h, "dialog:button::Restore defaults"); + assert!(!h.app.space_mouse.restore_pending && section_is_at_defaults(&h.app)); + let saved = h.app.prefs(); + let mut next = crate::scenario::Harness::new(); + next.app.preferences.space_mouse_speed = 2.5; + assert!(!section_is_at_defaults(&next.app)); + next.app.load_prefs(&saved); + assert!(section_is_at_defaults(&next.app), "the defaults are what was saved"); + assert_eq!(next.app.preferences.space_mouse_calibrations, calibrations, "and the calibration with them"); + assert!(!next.app.space_mouse.restore_pending); + } + + /// The visible Calibrate button on the offer's card and the one in Preferences both open the wizard + /// for the device, at its first screen, with Preferences open. + #[test] + fn the_calibrate_buttons_on_the_card_and_in_preferences_start_the_same_wizard() { + let wizard = |h: &crate::scenario::Harness| { + h.app.space_mouse.calibrating.as_ref().map(|(device, wizard)| (device.clone(), format!("{:?} {:?}", wizard.stage(), wizard.kind()))) + }; + let harness = || { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.space_mouse.device = Some("spacenavd".into()); + h.call("ui.resize", serde_json::json!({"width": 1600, "height": 4000})); + h + }; + // The card's. + let mut card = harness(); + card.frames(120); + assert!(card.app.space_mouse.offer_since.is_some() && card.app.space_mouse.calibrating.is_none()); + card.step(&serde_json::json!({"widget": "Calibrate…"})).unwrap(); + card.frames(5); + // Preferences'. + let mut prefs = harness(); + crate::prefs::open_at(&mut prefs.app, crate::prefs::PAGE_NAVIGATION); + prefs.frames(6); + prefs.frames(30); + assert!(prefs.app.space_mouse.calibrating.is_none()); + scroll_to_and_click(&mut prefs, "dialog:button:Calibration:Calibrate…"); + assert!(card.app.prefs_window.open && prefs.app.prefs_window.open); + assert!(wizard(&card).is_some(), "the card's button started it"); + assert_eq!(wizard(&card), wizard(&prefs), "and Preferences' starts the same one"); + } + + /// Direct or Automatic chosen with the device present but unopenable: the daemon is read, and Preferences + /// says so next to the setting instead of leaving "Direct (hidraw)" to imply the device. Spacenavd + /// chosen, or the device itself read, or no device: no such note. + #[test] + fn preferences_says_when_the_daemon_is_read_instead_of_the_device_asked_for() { + use SpaceMouseDriver::{Automatic, Direct, Spacenavd}; + let note = crate::i18n::tr("ui.3d_mouse_driver_fallback").to_string(); + assert!(note.contains("spacenavd") && note.contains("could not be opened")); + for catalog in crate::i18n::LOCALES { + let text = crate::i18n::Locale::for_language(catalog.id).text("ui.3d_mouse_driver_fallback"); + assert!(text.chars().count() > 20 && text != "ui.3d_mouse_driver_fallback", "{}", catalog.id); + } + // (driver, device being read, device present) and whether the note shows. + let cases = [ + (Direct, "spacenavd", true, true), + (Automatic, "spacenavd", true, true), + (Spacenavd, "spacenavd", true, false), + (Direct, "hid 046d:c62b", true, false), + (Automatic, "hid 046d:c62b", true, false), + (Direct, "spacenavd", false, false), + ]; + for (driver, device, direct, shown) in cases { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.space_mouse_driver = driver; + h.app.space_mouse.device = Some(device.into()); + h.app.space_mouse.drivers = Some(crate::space_mouse::DriversPresent { spacenavd: true, direct, denied: false }); + h.call("ui.resize", serde_json::json!({"width": 1600, "height": 4000})); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(6); + h.frames(30); + open_advanced(&mut h); + let up = h.widget(¬e).is_some(); + assert_eq!(up, shown, "{driver:?} reading {device}, device present {direct}"); + // Whatever it says, no calibration moves between keys. + assert!(h.app.preferences.space_mouse_calibrations.is_empty()); + } + } + + /// The section's buttons keep inside the page in every language, at the dialog's width (which the + /// window does not narrow): the arming Restore button, Reset axis assignment, Reset view under the + /// test model, and the buttons' own reset. + #[test] + fn the_3d_mouse_buttons_fit_the_page_in_every_language() { + let keys = ["ui.3d_mouse_restore", "ui.3d_mouse_reset_axes", "ui.3d_mouse_reset_view", "ui.3d_mouse_buttons_reset"]; + let mut too_wide = Vec::new(); + for catalog in crate::i18n::LOCALES { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.language = catalog.id.to_string(); + h.app.space_mouse.device = Some("hid 046d:c62b".into()); + let axes = std::array::from_fn(|source| solidcraft_space_mouse::AxisCalibration { + source, + reversed: false, + rest: 0, + dead_zone: 0, + full: [350; 2], + }); + h.app.preferences.space_mouse_calibrations.insert( + "hid 046d:c62b".into(), + solidcraft_space_mouse::Calibration { dead_zone_share: 0.0, kind: solidcraft_space_mouse::Kind::ReturnToCenter, axes }, + ); + h.app.preferences.space_mouse_buttons.insert("hid 046d:c62b".into(), [(1, crate::space_mouse::ButtonJob::Settings)].into()); + // The axis assignment is changed, so its reset button is enabled and drawn. + h.app.preferences.space_mouse_axis_source = [1, 0, 2, 3, 4, 5]; + h.call("ui.resize", serde_json::json!({"width": 1600, "height": 4000})); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(6); + scroll_to_and_click(&mut h, &format!("dialog:section:{}", crate::i18n::Locale::for_language(catalog.id).text("Advanced"))); + h.frames(10); + // The restore question is up, so its whole text can be checked too. + h.app.space_mouse.restore_pending = true; + // The frame's language is only set while it runs, so the texts come from the catalog itself. + let text = |key: &str| crate::i18n::Locale::for_language(catalog.id).text(key).to_string(); + h.frames(30); + let body = crate::scenario::rect_of("prefs:page_body").expect("the page body"); + // The question: all of it is laid out (its box is as tall as its wrapped text needs) and the + // buttons start below it. + let question = text("ui.3d_mouse_restore_ask"); + match crate::scenario::rect_of("dialog:hint:space_mouse_restore_ask") { + Some(note) => { + let t = crate::theme::Tokens::get(); + let needed = h.ctx.fonts_mut(|fonts| { + fonts.layout(question.clone(), egui::FontId::proportional(t.font_small), egui::Color32::WHITE, note.width()).size().y + }); + if note.height() + 0.5 < needed { + too_wide.push(format!("{} question is {:.0} px tall, its text needs {needed:.0}", catalog.id, note.height())); + } + if note.left() < body.left() - 0.5 || note.right() > body.right() + 0.5 { + too_wide.push(format!("{} question {:.0}..{:.0} outside the page", catalog.id, note.left(), note.right())); + } + let cancel = crate::scenario::rect_of(&format!("dialog:button::{}", text("ui.cancel"))); + if cancel.is_some_and(|cancel| cancel.top() < note.bottom() - 0.5) { + too_wide.push(format!("{} the buttons overlap the question", catalog.id)); + } + } + None => too_wide.push(format!("{} question not drawn", catalog.id)), + } + for key in keys { + let label = text(key); + let Some(rect) = crate::scenario::rect_of(&format!("dialog:button::{label}")) else { + too_wide.push(format!("{} {key}: not drawn", catalog.id)); + continue; + }; + if rect.right() > body.right() + 0.5 || rect.left() < body.left() - 0.5 { + too_wide.push(format!( + "{} {key} \"{label}\": {:.0}..{:.0} outside the page {:.0}..{:.0}", + catalog.id, + rect.left(), + rect.right(), + body.left(), + body.right() + )); + } + } + } + assert!(too_wide.is_empty(), "{}", too_wide.join("\n")); + } + + /// The widest of the card's button labels stays well inside the narrowest card (346 px wide at a 760 px + /// window, less its padding) in every language, so a button never has to be wider than its card. + #[test] + fn the_offers_buttons_fit_the_narrowest_card_in_every_language() { + let ctx = crate::fonts::test_context(); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + let font = egui::FontId::proportional(crate::theme::Tokens::get().font_label); + let mut wide = Vec::new(); + for catalog in crate::i18n::LOCALES { + use crate::space_mouse_offer::Action; + for key in [Action::Swap, Action::Calibrate, Action::Never, Action::Close].map(|action| action.label()) { + let label = crate::i18n::Locale::for_language(catalog.id).text(key).to_string(); + let width = ctx.fonts_mut(|fonts| fonts.layout_no_wrap(label.clone(), font.clone(), egui::Color32::WHITE).size().x); + if width > 250.0 { + wide.push(format!("{} {key} \"{label}\" is {width:.0} px", catalog.id)); + } + } + } + assert!(wide.is_empty(), "{}", wide.join("\n")); + } + + /// The circles' tooltips come from the one function the rows' labels come from, after a + /// reassignment, for both kinds of driver mapping (and none), and an inverted axis reads the same. + #[test] + fn the_circles_tooltips_say_what_the_rows_say_after_a_reassignment() { + use crate::space_mouse::{DriverMapping, SAME_AXES, reassign, row_label, stories}; + let shares = [[0.1_f32, 0.2]; 6]; + let mut inverted = DriverMapping::object_mode(); + for rule in &mut inverted.axes { + rule.reversed = !rule.reversed; + } + let mappings = [Some(DriverMapping::default()), Some(DriverMapping::object_mode()), Some(inverted), None]; + for mapping in mappings { + let mut source = SAME_AXES; + reassign(&mut source, 2, 1); + let said = stories("en", mapping, source); + let say = |row: usize| crate::i18n::Locale::for_language("en").format(row_label(mapping, row), &[("n", &(row + 1).to_string())]); + // Motion 1 is read by row 2 now, motion 2 by row 1; the others by their own rows. + assert_eq!(said[1], say(2), "{mapping:?}"); + assert_eq!(said[2], say(1), "{mapping:?}"); + assert_eq!(said[0], say(0)); + let tip = crate::space_mouse_calibration::pad_tooltip(&shares, (0, 1), &said); + assert_eq!(tip, format!("X −10 % +20 % → {}\nY −10 % +20 % → {}", say(0), say(2)), "{mapping:?}"); + // Invert is not in the story: the same words with every axis inverted. + let mut flipped = mapping; + if let Some(mapping) = flipped.as_mut() { + mapping.axes.iter_mut().for_each(|rule| rule.reversed = !rule.reversed); + } + assert_eq!(stories("en", flipped, source), said); + } + // A motion nobody reads says nothing, so no arrow. + let none = stories("en", Some(DriverMapping::default()), [0, 0, 0, 0, 0, 0]); + assert!(none[3].is_empty()); + assert_eq!(crate::space_mouse_calibration::pad_tooltip(&shares, (3, 4), &none), "Rx −10 % +20 %\nRy −10 % +20 %"); + } + + /// The circles say what the view does with their axes in the rows' own words, and keep saying it + /// after an axis is reassigned. + #[test] + fn the_circles_and_the_rows_tell_the_same_story_after_a_reassignment() { + use crate::space_mouse::{DriverMapping, SAME_AXES, motion_story, reassign, row_label}; + let mapping = Some(DriverMapping::default()); + // Unchanged: each motion is read by the row of its own number. + for motion in 0..6 { + assert_eq!(motion_story(mapping, SAME_AXES, motion), Some(row_label(mapping, motion))); + } + // Row 2 (lift) now reads motion 1 (push): the motion's story is that row's label, and row 1 reads motion 2. + let mut source = SAME_AXES; + reassign(&mut source, 2, 1); + assert_eq!(motion_story(mapping, source, 1), Some(row_label(mapping, 2))); + assert_eq!(motion_story(mapping, source, 2), Some(row_label(mapping, 1))); + assert_ne!(motion_story(mapping, source, 1), motion_story(mapping, SAME_AXES, 1)); + // Not one motion per row: a motion nobody reads has no story. + assert_eq!(motion_story(mapping, [0, 0, 0, 0, 0, 0], 3), None); + assert!(crate::i18n::tr("ui.3d_mouse_circles_help").contains("test model")); + } + + /// The "wiggle it" hint is a visible line as well as a tooltip, only while a reader is reachable and + /// silent; the section's own header carries no badge any more. + #[test] + fn a_visible_line_says_what_the_3d_mouse_waits_for() { + assert_eq!(crate::i18n::tr("ui.3d_mouse_waiting"), "Waiting for Movement"); + assert_eq!(crate::i18n::tr("ui.3d_mouse_reset_view"), "Reset view"); + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.space_mouse.device = None; + h.app.space_mouse.drivers = Some(crate::space_mouse::DriversPresent { spacenavd: true, direct: false, denied: false }); + h.call("ui.resize", serde_json::json!({"width": 1600, "height": 4000})); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_NAVIGATION); + h.frames(5); + assert!(crate::scenario::rect_of("dialog:section:3D mouse").is_some(), "the section is drawn with the kit's header"); + assert!(crate::scenario::rect_of("dialog:section:3D mouse:count").is_none()); + assert!(crate::scenario::rect_of("dialog:hint:space_mouse_wiggle").is_some()); + } + + /// The boat's Reset view puts the boat back and nothing else: calibration, sensitivity, axis + /// assignment and the document's camera stay. Clicked as a person would. + #[test] + fn reset_view_is_scoped_to_the_test_model() { + let mut h = changed_3d_mouse_settings(Some("hid 046d:c62b")); + h.frames(10); + // The boat has been turned. + let mut boat = crate::test_boat::Boat::new(30.0); + boat.cam.yaw += 1.0; + h.app.space_mouse.boat = Some(boat); + let before = (h.app.cam, h.app.preferences.clone()); + scroll_to_and_click(&mut h, "dialog:button::Reset view"); + assert!( + h.app.space_mouse.boat.is_none() + || h.app.space_mouse.boat.as_ref().is_some_and(|boat| boat.cam.yaw == crate::test_boat::Boat::new(30.0).cam.yaw), + "the boat is back" + ); + assert_eq!(h.app.cam, before.0, "the document's camera"); + assert_eq!(h.app.preferences, before.1, "every setting, calibration included"); + assert_eq!(crate::i18n::tr("ui.3d_mouse_reset_view"), "Reset view"); + } + + /// The "wiggle it" hint exists in every catalog and is a visible line while no device is confirmed, + /// gone once there is one. + #[test] + fn the_wiggle_hint_has_text_and_shows_until_a_device_is_confirmed() { + assert_eq!(crate::i18n::tr("ui.3d_mouse_wiggle"), "If you have one plugged in, wiggle it."); + for catalog in crate::i18n::LOCALES { + let text = crate::i18n::Locale::for_language(catalog.id).text("ui.3d_mouse_wiggle"); + assert!(!text.is_empty() && text != "ui.3d_mouse_wiggle", "{}", catalog.id); + } + let mut h = changed_3d_mouse_settings(None); + h.app.space_mouse.drivers = Some(crate::space_mouse::DriversPresent { spacenavd: true, direct: false, denied: false }); + h.frames(10); + assert!(crate::scenario::rect_of("dialog:hint:space_mouse_wiggle").is_some(), "no device yet: the hint is a line"); + h.app.space_mouse.device = Some("spacenavd".into()); + h.frames(10); + assert!(crate::scenario::rect_of("dialog:hint:space_mouse_wiggle").is_none(), "confirmed: no hint"); + } + + /// A 3D mouse that is there but may not be read, with no spacenavd to ask instead: Preferences says so + /// in plain words and does not ask for a movement; with a daemon reachable it still waits for one. + #[test] + fn preferences_says_when_a_device_is_found_but_not_allowed() { + for catalog in crate::i18n::LOCALES { + for key in ["ui.3d_mouse_denied", "ui.3d_mouse_denied_short"] { + let text = crate::i18n::Locale::for_language(catalog.id).text(key); + assert!(text.chars().count() > 5 && text != key, "{} {key}", catalog.id); + } + } + assert!(crate::i18n::tr("ui.3d_mouse_denied").contains("udev")); + let cases = [ + // (spacenavd there, device found, denied) and whether the denied line shows. + (false, true, true, true), + (false, true, false, false), + (true, true, true, false), + (false, false, false, false), + ]; + for (spacenavd, direct, denied, shown) in cases { + let mut h = changed_3d_mouse_settings(None); + h.app.space_mouse.drivers = Some(crate::space_mouse::DriversPresent { spacenavd, direct, denied }); + h.frames(10); + let said = crate::scenario::rect_of("dialog:hint:space_mouse_denied").is_some(); + assert_eq!(said, shown, "spacenavd {spacenavd}, found {direct}, denied {denied}"); + let wiggle = crate::scenario::rect_of("dialog:hint:space_mouse_wiggle").is_some(); + assert_eq!(wiggle, !shown, "the hint to wiggle shows only where waiting can help"); + assert_eq!(super::waiting_for_a_record(h.app.space_mouse.drivers), spacenavd || (direct && !denied)); + } + } + + /// The dialog's Restore Defaults on the page that holds the 3D mouse section resets the page, and the + /// 3D mice already offered a calibration stay offered (like their calibrations and button mappings): + /// the offer does not come back for every device. + #[test] + fn the_dialogs_restore_defaults_keeps_the_offered_set_with_the_calibrations() { + let mut h = changed_3d_mouse_settings(Some("hid 046d:c62b")); + h.app.preferences.space_mouse_offered.insert("hid 046d:c62b".into()); + h.app.preferences.space_mouse_buttons.insert("hid 046d:c62b".into(), [(1, crate::space_mouse::ButtonJob::Settings)].into()); + let (offered, calibrations, buttons) = ( + h.app.preferences.space_mouse_offered.clone(), + h.app.preferences.space_mouse_calibrations.clone(), + h.app.preferences.space_mouse_buttons.clone(), + ); + h.call("ui.prefs", serde_json::json!({"button": "defaults"})); + h.frames(3); + assert!(h.app.preferences.space_mouse_speed == Prefs::default().space_mouse_speed, "the page was reset"); + assert_eq!(h.app.preferences.space_mouse_offered, offered); + assert_eq!(h.app.preferences.space_mouse_calibrations, calibrations); + assert_eq!(h.app.preferences.space_mouse_buttons, buttons); + } + + /// The first screen of the calibration (which kind of device) fits at the window's widths: + /// both pictures are inside it, side by side or one under the other. + #[test] + fn the_calibration_choose_screen_fits_at_every_width() { + for width in [300.0_f32, 360.0, 520.0, 900.0] { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.space_mouse.device = Some("hid 046d:c62b".into()); + crate::space_mouse_calibration::start(&mut app); + let ctx = crate::fonts::test_context(); + for _ in 0..6 { + crate::scenario::clear_handles(); + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 900.0))), + focused: true, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| crate::space_mouse_calibration::show(&mut app, ui.ctx())); + output.textures_delta.clear(); + } + let window = crate::scenario::rect_of("dialog:window").expect("the window is drawn"); + let pictures = crate::scenario::rects("space_mouse:picture"); + assert_eq!(pictures.len(), 2, "width {width}: both kinds are offered"); + for (_, picture) in &pictures { + assert!(window.contains_rect(*picture), "width {width}: {picture:?} is outside {window:?}"); + } + assert!(!pictures[0].1.intersects(pictures[1].1), "width {width}: the pictures overlap"); + } + } + + /// The six readings in the calibration window are a clean grid whatever the values: each name + /// and its number are in their own column, never wrap or overlap, each number is centred under + /// its name, and the block is the same height for every value, so the window does not jitter. + #[test] + fn the_calibration_readings_are_a_clean_grid_of_constant_height() { + let sets: [[i16; 6]; 6] = [[0; 6], [-1; 6], [350; 6], [-350; 6], [i16::MAX; 6], [i16::MIN; 6]]; + for width in [360.0_f32, 520.0, 900.0] { + let mut heights = Vec::new(); + for values in sets { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.space_mouse.device = Some("hid 046d:c62b".into()); + app.space_mouse.raw = values.into(); + crate::space_mouse_calibration::start(&mut app); + let ctx = crate::fonts::test_context(); + for _ in 0..4 { + crate::scenario::clear_handles(); + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 900.0))), + focused: true, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| crate::space_mouse_calibration::show(&mut app, ui.ctx())); + output.textures_delta.clear(); + } + let rect = |kind: &str, i: usize| crate::scenario::rect_of(&format!("space_mouse:reading_{kind}:{i}")).expect("drawn"); + let all: Vec = (0..6).flat_map(|i| [rect("name", i), rect("value", i)]).collect(); + for (a, first) in all.iter().enumerate() { + for second in &all[a + 1..] { + assert!(!first.intersects(*second), "width {width} {values:?}: {first:?} overlaps {second:?}"); + } + } + for i in 0..6 { + let (name, value) = (rect("name", i), rect("value", i)); + assert!((name.center().x - value.center().x).abs() <= 1.0, "width {width} {values:?}: number {i} is not under its name"); + assert!(value.top() >= name.bottom(), "number {i} is not on the line below"); + assert_eq!(name.top(), rect("name", 0).top(), "the names share a baseline"); + assert_eq!(value.top(), rect("value", 0).top(), "the numbers share a baseline"); + assert!(value.width() <= 48.0, "{values:?}: number {i} is wider than its column"); + } + heights.push(crate::scenario::rect_of("space_mouse:reading_block").expect("block").height()); + } + assert!(heights.windows(2).all(|pair| pair[0] == pair[1]), "width {width}: the block's height depends on the values: {heights:?}"); + } + } + + /// On the last screen, with the pictures and pads, the window is the same size for any live reading. + #[test] + fn the_calibration_window_keeps_its_size_while_the_cap_moves() { + let mut windows = Vec::new(); + for values in [[0_i16; 6], [-1; 6], [350; 6], [-350; 6], [i16::MAX; 6], [i16::MIN; 6], [159, -5, 0, 32, -17, 5]] { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.space_mouse.device = Some("hid 046d:c62b".into()); + crate::space_mouse_calibration::start(&mut app); + { + let wizard = &mut app.space_mouse.calibrating.as_mut().unwrap().1; + wizard.choose(solidcraft_space_mouse::Kind::ReturnToCenter); + let hold = |wizard: &mut solidcraft_space_mouse::Wizard, reading: [i16; 6], seconds: f64| { + for _ in 0..(seconds / 0.02).round() as usize { + wizard.feed(reading, 0.02); + } + }; + hold(wizard, [0; 6], 1.6); + hold(wizard, [0; 6], 2.6); + for step in solidcraft_space_mouse::STEPS { + let mut raw = [0_i16; 6]; + raw[step.axis] = if step.positive { 300 } else { -300 }; + hold(wizard, raw, 0.5); + hold(wizard, [0; 6], 0.1); + } + assert!(matches!(wizard.result(), Some(Ok(_))), "the calibration reached its result screen"); + } + app.space_mouse.raw = values.into(); + let ctx = crate::fonts::test_context(); + for _ in 0..4 { + crate::scenario::clear_handles(); + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 900.0))), + focused: true, + ..Default::default() + }; + let mut output = ctx.run_ui(input, |ui| crate::space_mouse_calibration::show(&mut app, ui.ctx())); + output.textures_delta.clear(); + } + windows.push(crate::scenario::rect_of("dialog:window").expect("the window is drawn")); + } + assert!(windows.windows(2).all(|pair| pair[0] == pair[1]), "the window changes with the readings: {windows:?}"); + } + + /// One button job this build can't read (a newer release's) costs that button, not the lot. + #[test] + fn one_unreadable_button_job_keeps_the_others() { + use crate::space_mouse::{ButtonJob, ButtonKey}; + let saved = serde_json::json!({ "space_mouse_buttons": { + "hid 046d:c62b": { "1": { "key": "esc" }, "2": { "teleport": 3 }, "x": "settings", "3": "settings" }, + "hid 256f:c63a": { "4": { "view": "top" } }, + "spacenavd": 7, + } }); + let prefs: super::Prefs = serde_json::from_value(saved).expect("reads"); + let jobs = &prefs.space_mouse_buttons; + assert_eq!(jobs["hid 046d:c62b"], [(1, ButtonJob::Key(ButtonKey::Esc)), (3, ButtonJob::Settings)].into()); + assert_eq!(jobs["hid 256f:c63a"], [(4, ButtonJob::View("top".into()))].into()); + assert!(!jobs.contains_key("spacenavd")); + } + + /// A calibration as saved: the same text loads and is usable on 32 and 64 bits, and one saved + /// with the old `usize::MAX` (64-bit native) still reads as having no source on 64 bits. + #[test] + fn a_saved_calibration_with_no_source_reads_the_same_on_every_width() { + use solidcraft_space_mouse::{Calibration, NO_SOURCE}; + let axis = |source: &str, full: u32| format!(r#"{{"source":{source},"reversed":false,"rest":0,"dead_zone":3,"full":[{full},{full}]}}"#); + let json = |absent: &str| { + let axes = [axis("0", 300), axis("1", 300), axis("2", 300), axis(absent, 1), axis(absent, 1), axis("3", 300)].join(","); + format!(r#"{{"dead_zone_share":0.0,"kind":"Trackball","axes":[{axes}]}}"#) + }; + let fixed: Calibration = serde_json::from_str(&json("65535")).unwrap(); + assert_eq!(fixed.axes.map(|axis| axis.source), [0, 1, 2, NO_SOURCE, NO_SOURCE, 3]); + assert!(fixed.is_usable()); + assert_eq!(serde_json::to_string(&fixed.axes[3].source).unwrap(), "65535"); + #[cfg(target_pointer_width = "64")] + assert_eq!(serde_json::from_str::(&json("18446744073709551615")).unwrap(), fixed); + } + + #[test] + fn changing_preferences_page_cancels_shortcut_capture() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.prefs", json!({"open":"Keyboard Shortcuts"})); + h.step(&json!({"click":{"handle":"keymap:filter"}})).unwrap(); + h.step(&json!({"text":"solid.extrude"})).unwrap(); + h.step(&json!({"click":{"handle":"keymap:capture:solid.extrude"}})).unwrap(); + h.step(&json!({"key":"M","pressed":true})).unwrap(); + h.step(&json!({"click":{"handle":"prefs:page:General"}})).unwrap(); + assert!(!crate::keymap::capturing(&h.app)); + assert_eq!(crate::keymap::effective(&h.app, "solid.extrude").as_deref(), Some("E")); + h.frames(65); + assert_eq!(crate::keymap::effective(&h.app, "solid.extrude").as_deref(), Some("E")); + } + + #[test] + fn display_quality_cards_show_increasing_facet_detail() { + let mut app = super::SolveApp::new(Default::default(), Default::default()); + super::open_at(&mut app, super::PAGE_GRAPHICS); + let ctx = crate::fonts::test_context(); + let mut shapes = Vec::new(); + for _ in 0..3 { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), ..Default::default() }, + |ui| super::show(&mut app, ui.ctx()), + ); + shapes = std::mem::take(&mut out.shapes); + out.textures_delta.clear(); + } + let mut previous = 0; + for label in ["Coarse", "Normal", "Fine", "Ultra"] { + let card = crate::scenario::rect_of(&format!("prefs:option:{label}")).expect("quality card"); + let facets = shapes + .iter() + .filter_map(|shape| { + if let egui::Shape::Path(path) = &shape.shape { + path.points.iter().all(|p| card.contains(*p)).then_some(path.points.len()) + } else { + None + } + }) + .max() + .unwrap_or(0); + assert!(facets > previous, "{label} must visibly add detail to the preceding quality: {facets} <= {previous}"); + previous = facets; + } + } + + #[test] + fn moved_preferences_reset_only_on_their_new_page() { + use super::*; + let fields = [ + ("default_units", json!("ft"), PAGE_DESIGN), + ("length_decimals", json!(5), PAGE_DESIGN), + ("angle_decimals", json!(4), PAGE_DESIGN), + ("theme", json!("light"), PAGE_INTERFACE), + ("ui_scale", json!(1.25), PAGE_INTERFACE), + ("ui_font", json!("test font"), PAGE_INTERFACE), + ("layout", json!("compact"), PAGE_INTERFACE), + ("ribbon_labels", json!(false), PAGE_INTERFACE), + ("sketch_tab_always", json!(true), PAGE_INTERFACE), + ("dialog_buttons", json!("top"), PAGE_INTERFACE), + ("toast_place", json!("centre"), PAGE_INTERFACE), + ("timeline_left", json!(true), PAGE_INTERFACE), + ("timeline_under_browser", json!(true), PAGE_INTERFACE), + ("history_sketches", json!("under_feature"), PAGE_INTERFACE), + ("history_play_button", json!(false), PAGE_INTERFACE), + ("browser_float", json!(true), PAGE_INTERFACE), + ("browser_collapsed", json!(true), PAGE_INTERFACE), + ("browser_show", json!("hover"), PAGE_INTERFACE), + ("dialog_place", json!("left_column"), PAGE_INTERFACE), + ("color_vision", json!("protan"), PAGE_INTERFACE), + ("viewport_theme", json!("light"), PAGE_INTERFACE), + ("viewport_background", json!([255, 255, 255]), PAGE_INTERFACE), + ("view_confirm_corner", json!(true), PAGE_INTERFACE), + ("status_bar", json!(true), PAGE_INTERFACE), + ("nav", json!("blender"), PAGE_NAVIGATION), + ("look_at_anim", json!(false), PAGE_NAVIGATION), + ("selection_shift_add_only", json!(true), PAGE_SKETCH), + ("sketch_conflict_colour", json!(false), PAGE_SKETCH), + ("suppress_sketch_snap", json!(ModifierCombo::NONE), PAGE_SKETCH), + ("sketch_state_icons", json!(false), PAGE_SKETCH), + ("sketch_tracking_guides", json!(false), PAGE_SKETCH), + ("msaa", json!(8), PAGE_GRAPHICS), + ]; + let defaults = serde_json::to_value(Prefs::default()).unwrap(); + for (field, value, owner) in fields { + for page in 0..PAGES.len() { + let mut data = defaults.clone(); + data[field] = value.clone(); + let mut prefs: Prefs = serde_json::from_value(data).unwrap(); + reset_preferences(&mut prefs, page); + let result = serde_json::to_value(prefs).unwrap(); + assert_eq!(result[field], if page == owner { defaults[field].clone() } else { value.clone() }, "{field}, page {page}"); + } + } + } + + #[test] + fn page_aliases_and_transient_defaults_follow_the_new_groups() { + use super::*; + for name in ["Sketch", "Selection", "Sketch & selection"] { + assert_eq!(page_index(name), Some(PAGE_SKETCH)); + } + assert_eq!(page_index("Assistant"), Some(PAGE_AI)); + assert_eq!(page_index("Shortcuts"), Some(PAGE_SHORTCUTS)); + let mut app = SolveApp::new(Default::default(), Default::default()); + app.ui.agent_cursor.show = false; + app.ui.pick_bodies = true; + app.session.auto_project = false; + defaults(&mut app, PAGE_GENERAL); + assert!(!app.ui.agent_cursor.show); + assert!(app.ui.pick_bodies); + assert!(!app.session.auto_project); + defaults(&mut app, PAGE_AI); + let expected = SolveApp::new(Default::default(), Default::default()).ui.agent_cursor.show; + assert_eq!(app.ui.agent_cursor.show, expected); + defaults(&mut app, PAGE_SKETCH); + assert!(!app.ui.pick_bodies); + assert!(app.session.auto_project); + } + + fn hole_preset_row(name: &str) -> serde_json::Value { + serde_json::json!({ + "name": name, "style": "counterbore", "extent": "distance", + "diameter": "shaft_diameter + 0.2 mm", "depth": "0.5 in", + "cb_diameter": "10 mm", "cb_depth": "3 mm", "cs_diameter": "10 mm", + "cs_angle": "90 deg", "tip_angle": "118 deg", "tapped": true, "thread": "M5" + }) + } + + #[test] + fn hole_presets_corrupt_rows_and_limits_do_not_discard_other_preferences() { + use serde_json::json; + let good = hole_preset_row("Workshop"); + let mut oversized = hole_preset_row("Too long"); + oversized["diameter"] = json!("x".repeat(513)); + let mut duplicate = good.clone(); + duplicate["name"] = json!("WORKSHOP"); + let p = super::lenient(&json!({"length_decimals":4,"hole_presets":[null,good,oversized,duplicate,{"name":"incomplete"}]})); + assert_eq!(p.length_decimals, 4); + let rows = serde_json::to_value(&p.hole_presets).unwrap(); + assert_eq!(rows.as_array().unwrap().len(), 1); + assert_eq!(rows[0]["name"], "Workshop"); + assert_eq!(rows[0]["diameter"], "shaft_diameter + 0.2 mm"); + assert_eq!(rows[0]["depth"], "0.5 in"); + let corrupt = super::lenient(&json!({"length_decimals":3,"hole_presets":{"unexpected":true}})); + assert_eq!(corrupt.length_decimals, 3); + assert_eq!(serde_json::to_value(corrupt.hole_presets).unwrap(), json!([])); + let many: Vec<_> = (0..100).map(|i| hole_preset_row(&format!("Preset {i}"))).collect(); + let capped = super::lenient(&json!({"hole_presets":many})); + assert_eq!(serde_json::to_value(capped.hole_presets).unwrap().as_array().unwrap().len(), 64); + } + + #[test] + fn hole_presets_survive_application_preferences_roundtrip_and_page_resets() { + use serde_json::json; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let mut row = hole_preset_row("Fixture"); + row["thread_options"] = json!({"handedness":"left","full_length":false,"depth":"4 mm"}); + super::set(&mut app, &json!({"hole_presets":[row]})).unwrap(); + let expected = serde_json::to_value(&app.preferences.hole_presets).unwrap(); + assert_eq!(expected[0]["thread_options"]["handedness"], "left"); + for page in 0..super::PAGES.len() { + super::reset_preferences(&mut app.preferences, page); + } + assert_eq!(serde_json::to_value(&app.preferences.hole_presets).unwrap(), expected); + let saved = app.prefs(); + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&saved); + assert_eq!(serde_json::to_value(&other.preferences.hole_presets).unwrap(), expected); + assert!(other.session.doc.features.is_empty()); + } + + #[test] + fn hole_presets_keep_unknown_thread_options_for_safe_future_recall() { + use serde_json::json; + let mut row = hole_preset_row("Newer version"); + row["thread_options"] = json!({"starts":2}); + let p = super::lenient(&json!({"hole_presets":[row]})); + let saved = serde_json::to_value(p.hole_presets).unwrap(); + assert_eq!(saved[0]["thread_options"]["starts"], 2, "unknown thread semantics must not silently become the defaults"); + } + + /// The interface font (#1290): a font that can be read, or empty for the built-in one; saved + /// with the others and reset by Restore Defaults. + #[test] + fn ui_font_is_checked_saved_and_restored() { + use serde_json::json; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + assert_eq!(app.preferences.ui_font, ""); + let family = solidcraft_engine::sketch::DEFAULT_FONT_FAMILY; + let out = super::set(&mut app, &json!({ "ui_font": family })).unwrap(); + assert_eq!(out["ui_font"], family); + let e = super::set(&mut app, &json!({"ui_font": "No Such Font 1290"})).unwrap_err(); + assert!(e.contains("ui_font"), "{e}"); + assert_eq!(app.preferences.ui_font, family, "a refused font leaves the choice as it was"); + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.ui_font, family); + super::defaults(&mut app, super::PAGE_INTERFACE); + assert_eq!(app.preferences.ui_font, ""); + } + + /// Bodies folders (#4217): Several bodies only by default, also in preferences saved before it + /// existed. Each value is saved and read back; `ui.prefs` refuses anything else and changes + /// nothing, and saved preferences read such a value as the default and keep the rest. The + /// Interface page's segments set it, Cancel puts it back and the page's Restore Defaults resets it. + #[test] + fn bodies_folders_is_saved_restored_and_refuses_unknown_values() { + use super::*; + let mut h = crate::scenario::Harness::new(); + assert_eq!(h.app.preferences.browser_bodies_folders, BodiesFolders::Several); + assert_eq!(lenient(&json!({"theme": "light"})).browser_bodies_folders, BodiesFolders::Several, "saved before it existed"); + for (mode, id) in [(BodiesFolders::Always, "always"), (BodiesFolders::Several, "several"), (BodiesFolders::Never, "never")] { + assert_eq!(control(&mut h.app, &json!({"browser_bodies_folders": id})).unwrap()["browser_bodies_folders"], id); + let mut restored = SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.browser_bodies_folders, mode, "{id}"); + } + for bad in [json!("sometimes"), json!("Never"), json!(""), json!(2), json!(null), json!(["never"])] { + let before = h.app.preferences.clone(); + assert!(set(&mut h.app, &json!({"browser_bodies_folders": bad})).is_err(), "{bad}"); + assert_eq!(h.app.preferences, before, "{bad}: a refused value changes nothing"); + let saved = lenient(&json!({"browser_bodies_folders": bad, "theme": "light"})); + assert_eq!((saved.browser_bodies_folders, saved.theme.as_str()), (BodiesFolders::Several, "light"), "{bad}"); + } + h.call("ui.prefs", json!({"open": "Interface"})); + reveal_preference(&mut h, "dialog:Bodies folders:Always"); + h.step(&json!({"click": {"handle": "dialog:Bodies folders:Always"}})).unwrap(); + assert_eq!(h.app.preferences.browser_bodies_folders, BodiesFolders::Always); + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.browser_bodies_folders, BodiesFolders::Never, "Cancel puts it back"); + defaults(&mut h.app, PAGE_INTERFACE); + assert_eq!(h.app.preferences.browser_bodies_folders, BodiesFolders::Several, "Interface's Restore Defaults"); + } + + /// Theme files (#2255): a built-in one and an imported one turn on through `ui.prefs`, the + /// next frame draws with their colours (dark following the base), an export gives the theme + /// back complete, imported themes are saved with the preferences, Remove falls back to the + /// base and Cancel takes an import back. + #[test] + fn system_theme_tile_export_uses_os_brightness_without_selecting_it() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.preferences.theme = "light".into(); + app.ui.dark = false; + assert_eq!(theme_file(&app, "system", true)["base"], "dark"); + assert_eq!(theme_file(&app, "system", false)["base"], "light"); + assert_eq!(app.preferences.theme, "light"); + assert!(!app.ui.dark); + } + + /// The 3D view in the other theme's colours (#4146): `ui.prefs` sets it, the window keeps its + /// theme and the next frame draws the view from the other side, and it is saved with the + /// preferences. With a theme file on, the view takes the built-in Light or Dark colours. + #[test] + fn the_3d_view_takes_the_light_or_dark_themes_colours() { + use crate::theme::{ColorVision, Tokens}; + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + for (theme, view, dark, view_dark) in + [("light", "theme", false, false), ("dark", "light", true, false), ("dark", "dark", true, true), ("light", "dark", false, true)] + { + let out = h.call("ui.prefs", json!({"theme": theme, "viewport_theme": view})); + assert_eq!((out["result"]["dark"].as_bool(), out["result"]["viewport_dark"].as_bool()), (Some(dark), Some(view_dark)), "{out}"); + h.frames(2); + let t = Tokens::get(); + assert_eq!(t.panel, Tokens::themed(dark, ColorVision::Off).panel, "{theme}, {view}: the window"); + assert_eq!(t.viewport_top, Tokens::themed(view_dark, ColorVision::Off).viewport_top, "{theme}, {view}: the view"); + } + + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&h.app.prefs()); + assert_eq!((other.preferences.theme.as_str(), other.ui.dark, other.viewport_dark()), ("light", false, true)); + + let out = h.call("ui.prefs", json!({"theme": "gruvbox-dark-hard", "viewport_theme": "light"})); + assert_eq!((out["result"]["dark"].as_bool(), out["result"]["viewport_dark"].as_bool()), (Some(true), Some(false)), "{out}"); + h.frames(2); + let hard = crate::theme_files::find("gruvbox-dark-hard", &[]).map(crate::theme_files::resolve).unwrap(); + assert_eq!((Tokens::get().panel, Tokens::get().viewport_top), (hard.panel, Tokens::light().viewport_top)); + + // Asked for, an unknown value is refused; read from saved preferences, it is the default. + assert!(h.call("ui.prefs", json!({"viewport_theme": "dim"}))["error"].is_string()); + let read: crate::theme::ViewportTheme = serde_json::from_value(json!("dim")).unwrap(); + assert_eq!(read, crate::theme::ViewportTheme::Theme); + } + + /// The 3D view's background in one colour of the user's (#7688): `ui.prefs` sets it, the next + /// frame fills the view with it in either theme while the window keeps its colours, a picture + /// of the view has it too, and it is saved with the preferences. `null` gives back the theme's + /// gradient; a value that is not a colour is refused, and read from saved preferences it is + /// the gradient. + #[test] + fn the_3d_view_takes_a_background_colour_of_its_own() { + use crate::theme::{ColorVision, Tokens}; + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + assert_eq!(h.app.preferences.viewport_background, None); + for (theme, view_dark) in [("light", false), ("dark", true)] { + let out = h.call("ui.prefs", json!({"theme": theme, "viewport_background": [255, 255, 255]})); + assert!(out["error"].is_null(), "{out}"); + h.frames(2); + let (t, white) = (Tokens::get(), egui::Color32::WHITE); + assert_eq!((t.viewport_top, t.viewport_bottom, Tokens::view().viewport_top), (white, white, white), "{theme}"); + assert_eq!(t.panel, Tokens::themed(view_dark, ColorVision::Off).panel, "{theme}: the window"); + let scene = crate::control::view_scene(&h.app, solidcraft_engine::view::Guides::default()); + let white = solidcraft_engine::render::Rgb(255, 255, 255); + assert_eq!(scene.background, Some((white, white)), "{theme}: a picture of the view"); + } + + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&h.app.prefs()); + assert_eq!(other.preferences.viewport_background, Some([255, 255, 255])); + + h.call("ui.prefs", json!({"viewport_background": null})); + h.frames(2); + let (t, dark) = (Tokens::get(), Tokens::dark()); + assert_eq!((t.viewport_top, t.viewport_bottom), (dark.viewport_top, dark.viewport_bottom), "the theme's gradient again"); + + for bad in [json!([256, 0, 0]), json!("white"), json!([1, 2])] { + assert!(h.call("ui.prefs", json!({"viewport_background": bad}))["error"].is_string(), "{bad}"); + assert_eq!(lenient(&json!({"viewport_background": bad})).viewport_background, None, "{bad}"); + } + } + + /// The theme strip's Import… reads the theme file through `vfs`, like the other imports: in the + /// web app a picked file is kept there, where `std::fs` can't read it (#7643). On the disk it + /// is the same file; a folder scope active while it is read refuses a path outside it, which + /// shows the read goes through `vfs`. + #[test] + fn a_theme_pasted_or_dropped_on_the_interface_page_imports_and_other_pastes_pass_through() { + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let theme = |name: &str| format!(r##"{{"format":"solidcraft-theme/1","name":"{name}","base":"dark","colors":{{"panel":"#102030"}}}}"##); + let has = |h: &crate::scenario::Harness, id: &str| h.app.preferences.custom_themes.iter().any(|t| t.id == id); + + // Another page: a theme's text is left to the usual paste. + h.call("ui.prefs", json!({"open":"General"})); + h.frames(2); + h.frame_with(vec![egui::Event::Paste(theme("Elsewhere"))]); + assert!(!has(&h, "elsewhere")); + + // The Interface page: plain text is not a theme and changes nothing. + h.call("ui.prefs", json!({"open":"Interface"})); + h.frames(2); + let before = h.app.preferences.clone(); + h.frame_with(vec![egui::Event::Paste("just some words".into())]); + assert_eq!(h.app.preferences.custom_themes, before.custom_themes); + + // A theme's text imports and turns on, as Import… does with a file. + h.frame_with(vec![egui::Event::Paste(theme("Pasted"))]); + assert!(has(&h, "pasted"), "{:?}", h.app.preferences.custom_themes.iter().map(|t| &t.id).collect::>()); + assert_eq!(h.app.preferences.theme, "pasted"); + + // An invalid theme says why, and imports nothing. + h.frame_with(vec![egui::Event::Paste(r#"{"format":"solidcraft-theme/1","name":"Bad","base":"sideways"}"#.into())]); + assert!(!has(&h, "bad")); + + // A file dropped on the Import tile is a theme to import, not a design to open. + h.frames(2); + let tile = h.app.prefs_window.import_tile.expect("the Import tile is drawn on the Interface page"); + let dir = std::env::temp_dir().join(format!("solidcraft-theme-drop-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("dropped.json"); + std::fs::write(&file, theme("Dropped")).unwrap(); + #[derive(Debug)] + struct File(std::path::PathBuf); + impl egui::DroppedFile for File { + fn path(&self) -> &std::path::Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + std::fs::read(&self.0).map_err(|e| e.to_string()) + } + } + let tabs = h.app.docs.count(); + h.frame_with(vec![egui::Event::PointerMoved(tile.center())]); + h.drop_files(tile.center(), vec![std::sync::Arc::new(File(file)) as egui::DroppedFileHandle]); + h.frames(2); + assert!(has(&h, "dropped")); + assert_eq!(h.app.docs.count(), tabs, "the drop opened no design"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn theme_import_reads_through_vfs() { + use serde_json::json; + use solidcraft_engine::io::vfs; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.prefs", json!({"theme": "dark", "open": "Interface"})); + h.frames(2); + super::reveal_preference(&mut h, "dialog:Import…"); + let (root, out) = (h.dir.join("root"), h.dir.join("out")); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&out).unwrap(); + let file = json!({"format": "solidcraft-theme/1", "name": "Paper", "base": "light", "colors": {"panel": "#fffdf0"}}); + for (path, inside) in [(out.join("Paper.json"), false), (root.join("Paper.json"), true)] { + std::fs::write(&path, file.to_string()).unwrap(); + let answer = path.to_string_lossy().to_string(); + h.app.services.pick_open = Some(Box::new(move |_| Box::pin(std::future::ready(Some(answer.clone()))))); + h.app.status = None; + vfs::scoped(Some(vfs::PathScope::new([root.clone()])), || { + h.step(&json!({"click":{"handle":"dialog:Import…"}})).unwrap(); + h.frames(4); + }); + let status = h.app.status.clone().map(|(text, ..)| text); + if inside { + assert_eq!(status.as_deref(), Some("Theme imported: Paper")); + assert_eq!(h.app.preferences.theme, "paper"); + } else { + assert!(status.as_deref().is_some_and(|s| s.contains("outside the folders this agent may use")), "{status:?}"); + assert!(h.app.preferences.custom_themes.is_empty(), "nothing imported"); + } + } + } + + #[test] + fn a_followed_theme_file_applies_reloads_keeps_the_last_good_theme_and_the_flag_is_not_saved() { + use crate::theme::Tokens; + use egui::Color32; + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + assert_eq!(h.app.preferences.theme_follow, "", "off by default"); + let out = h.call("ui.prefs", json!({})); + assert!(out["result"]["theme_followed"].is_null() && out["result"]["theme_follow_error"].is_null(), "{out}"); + + let dir = std::env::temp_dir().join(format!("solidcraft-prefs-follow-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("live.json"); + let path = file.to_string_lossy().to_string(); + let write = |panel: &str, extra: &str| { + let text = format!(r##"{{"format":"solidcraft-theme/1","name":"Live","base":"light","colors":{{"panel":"{panel}"{extra}}}}}"##); + std::fs::write(&file, text).unwrap(); + }; + write("#102030", ""); + let out = h.call("ui.prefs", json!({"theme_follow": path})); + assert_eq!( + (out["result"]["theme_follow"].as_str(), out["result"]["theme_followed"].as_str()), + (Some(path.as_str()), Some(path.as_str())), + "{out}" + ); + assert!(out["result"]["theme_follow_error"].is_null(), "{out}"); + h.frames(2); + assert_eq!(Tokens::get().panel, Color32::from_rgb(0x10, 0x20, 0x30)); + assert!(!h.app.ui.dark, "the file's base"); + + // Another tool rewrites it: reloaded within the poll interval, without a restart. + write("#405060", r##","accent":"#aa3300""##); + h.frames(70); + assert_eq!(Tokens::get().panel, Color32::from_rgb(0x40, 0x50, 0x60)); + + // Broken or missing: the last good theme stays on and the reply says why. + std::fs::write(&file, "{\"format\": \"solidcraft-theme/1\", \"na").unwrap(); + h.frames(70); + assert_eq!(Tokens::get().panel, Color32::from_rgb(0x40, 0x50, 0x60)); + let out = h.call("ui.prefs", json!({})); + assert!(out["result"]["theme_follow_error"].as_str().is_some_and(|e| e.contains("not a theme file")), "{out}"); + std::fs::remove_file(&file).unwrap(); + let out = h.call("ui.prefs", json!({"theme_follow": path})); + assert!(out["result"]["theme_follow_error"].as_str().is_some_and(|e| e.contains("can't read")), "{out}"); + + // Choosing a theme, or "", stops following. + let out = h.call("ui.prefs", json!({"theme": "dark"})); + assert!(out["result"]["theme_followed"].is_null() && out["result"]["theme_follow"] == "", "{out}"); + h.frames(2); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + + // The launch flag follows a file for this run only: the saved preferences never name it. + write("#708090", ""); + follow_theme_file_for_run(&mut h.app, &path).unwrap(); + h.frames(2); + assert_eq!(Tokens::get().panel, Color32::from_rgb(0x70, 0x80, 0x90)); + assert_eq!(h.call("ui.prefs", json!({}))["result"]["theme_followed"].as_str(), Some(path.as_str())); + assert_eq!(h.app.preferences.theme_follow, ""); + assert!(!h.app.prefs().contains("live.json")); + h.call("ui.prefs", json!({"theme_follow": ""})); + h.frames(2); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + + // Hostile values are refused; the browser has no files to follow. + assert!(h.call("ui.prefs", json!({"theme_follow": 5}))["error"].is_string()); + assert!(h.call("ui.prefs", json!({"theme_follow": "a\nb"}))["error"].is_string()); + assert!(h.call("ui.prefs", json!({"theme_follow": "x".repeat(5000)}))["error"].is_string()); + let web = set_theme_follow(&mut h.app, &json!(path), false).unwrap_err(); + assert!(web.contains("not available in the browser"), "{web}"); + assert_eq!(h.app.preferences.theme_follow, ""); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn theme_files_import_apply_export_save_and_remove() { + use crate::theme::{ColorVision, Tokens}; + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + let out = h.call("ui.prefs", json!({"theme": "gruvbox-dark-hard"})); + assert_eq!(out["result"]["theme"], "gruvbox-dark-hard", "{out}"); + assert!(out["result"]["theme_ids"].as_array().is_some_and(|ids| ids.len() == 3 + crate::theme_files::builtin().len()), "{out}"); + h.frames(2); + let hard = crate::theme_files::find("gruvbox-dark-hard", &[]).map(crate::theme_files::resolve).unwrap(); + assert!(h.app.ui.dark); + assert_eq!(Tokens::get().panel, hard.panel); + assert_eq!( + crate::viewport::scene_palette(true, ColorVision::Off).background.0, + solidcraft_engine::render::Rgb(hard.viewport_top.r(), hard.viewport_top.g(), hard.viewport_top.b()) + ); + + let file = json!({"format": "solidcraft-theme/1", "name": "Paper", "base": "light", "colors": {"panel": "#fffdf0", "accent": "#aa3300"}, "borders":{"primary":{"width":2,"color":"#ffffff"},"tertiary":{"width":0,"color":"#000000"}}, "radii": {"radius_sm": 0, "control_radius": 0, "radius_xl": 16}}); + let out = h.call("ui.prefs", json!({"theme_import": file, "theme_export": true})); + assert_eq!(out["result"]["theme_imported"], "paper", "{out}"); + assert_eq!((out["result"]["theme"].as_str(), out["result"]["dark"].as_bool()), (Some("paper"), Some(false))); + let exported = &out["result"]["theme_file"]; + assert_eq!((exported["name"].as_str(), exported["base"].as_str()), (Some("Paper"), Some("light"))); + assert_eq!(exported["colors"]["panel"], "#fffdf0"); + assert_eq!(exported["radii"]["control_radius"], 0); + assert_eq!(exported["radii"]["radius_xl"], 16); + assert_eq!(exported["radii"]["radius_md"], 6); + assert_eq!(exported["borders"]["primary"]["width"], 2.0); + assert_eq!(exported["colors"]["text"].as_str().map(str::len), Some(7), "an export is complete: {exported}"); + h.frames(2); + assert_eq!((Tokens::get().panel, Tokens::get().text), (egui::Color32::from_rgb(0xff, 0xfd, 0xf0), Tokens::light().text)); + assert_eq!((Tokens::get().control_radius, Tokens::get().radius_xl), (0, 16)); + let invalid = h.call( + "ui.prefs", + json!({"theme_import": {"format": "solidcraft-theme/1", "name": "Bad", "base": "dark", "radii": {"control_radius": -1}}}), + ); + assert!(invalid["error"].as_str().is_some_and(|e| e.contains("radii.control_radius"))); + let out = h.call( + "ui.prefs", + json!({"theme_import": "{\"format\":\"solidcraft-theme/1\",\"name\":\"x\",\"base\":\"dark\",\"colors\":{\"nope\":\"#000000\"}}"}), + ); + assert!(out["error"].as_str().is_some_and(|e| e.contains("nope")), "{out}"); + assert_eq!(h.app.preferences.theme, "paper", "a refused file changes nothing"); + assert!(h.call("ui.prefs", json!({"theme": "no-such-theme"}))["error"].is_string()); + + let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + other.load_prefs(&h.app.prefs()); + assert_eq!((other.preferences.theme.as_str(), other.preferences.custom_themes.len()), ("paper", 1)); + assert_eq!(other.preferences.custom_themes[0].radii, h.app.preferences.custom_themes[0].radii); + assert_eq!(other.preferences.custom_themes[0].borders, h.app.preferences.custom_themes[0].borders); + + let out = h.call("ui.prefs", json!({"theme_remove": "paper"})); + assert_eq!((out["result"]["theme"].as_str(), out["result"]["dark"].as_bool()), (Some("light"), Some(false)), "{out}"); + assert!(h.app.preferences.custom_themes.is_empty()); + assert!(h.call("ui.prefs", json!({"theme_remove": "paper"}))["error"].is_string()); + + h.call("ui.prefs", json!({"theme": "dark"})); + h.call("ui.prefs", json!({"open": "Interface"})); + h.call("ui.prefs", json!({"theme_import": file})); + let out = h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(out["result"]["theme"], "dark", "{out}"); + assert!(h.app.preferences.custom_themes.is_empty(), "Cancel takes the import back"); + h.frames(2); + assert_eq!(Tokens::get().panel, Tokens::dark().panel); + assert_eq!((Tokens::get().control_radius, Tokens::get().radius_xl), (6, 10)); + } + + /// A theme tile's Export… writes the theme file through `vfs`, like the other saves, so the + /// web app hands it out as a download (#7192). On the disk it is the same file; a folder scope + /// active while it is written refuses a path outside it, which shows the write goes through + /// `vfs`. + #[test] + fn theme_export_writes_through_vfs() { + use serde_json::json; + use solidcraft_engine::io::vfs; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.prefs", json!({"theme": "dark", "open": "Interface"})); + h.frames(2); + super::reveal_preference(&mut h, "prefs:theme_tile:dark"); + let (root, out) = (h.dir.join("root"), h.dir.join("out")); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&out).unwrap(); + for (path, inside) in [(root.join("Dark.json"), true), (out.join("Dark.json"), false)] { + let answer = path.to_string_lossy().to_string(); + h.app.services.pick_save = Some(Box::new(move |_, _| Box::pin(std::future::ready(Some(answer.clone()))))); + h.app.status = None; + vfs::scoped(Some(vfs::PathScope::new([root.clone()])), || { + h.step(&json!({"click":{"handle":"prefs:theme_tile:dark"},"button":"right"})).unwrap(); + h.step(&json!({"click":{"handle":"menu:theme_export"}})).unwrap(); + h.frames(4); + }); + let status = h.app.status.clone().map(|(text, ..)| text); + if inside { + assert_eq!(status, None); + let file: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(file, super::theme_file(&h.app, "dark", true)); + } else { + assert!(status.as_deref().is_some_and(|s| s.contains("outside the folders this agent may use")), "{status:?}"); + assert!(!path.exists(), "nothing written outside"); + } + } + } + + /// Picking a font closes the font list, not the Preferences window's body: that folded the + /// window to its title bar, and egui kept it folded between runs (#1800). A window folded by + /// an earlier release unfolds when Preferences opens. + #[test] + fn picking_a_font_keeps_the_preferences_window_unfolded() { + use egui::collapsing_header::CollapsingState; + use serde_json::json; + let body = egui::Id::new("sc_prefs").with("collapsing"); + let folded = |h: &crate::scenario::Harness| CollapsingState::load(&h.ctx, body).is_some_and(|s| !s.is_open()); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open":"Interface"})); + super::reveal_preference(&mut h, "prefs:ui_font"); + let combo = crate::scenario::handle_at("prefs:ui_font").unwrap(); + h.call("ui.click", json!({"x":combo.x,"y":combo.y})); + let builtin = crate::scenario::handle_at("prefs:font_builtin").expect("the font list is open"); + h.call("ui.click", json!({"x":builtin.x,"y":builtin.y})); + h.frames(2); + assert!(!folded(&h), "picking a font must not fold the Preferences window"); + assert!(crate::scenario::handle_at("prefs:font_builtin").is_none(), "the font list closes"); + assert!(crate::scenario::rect_of("prefs:ok").is_some(), "the window's body is still drawn"); + h.call("ui.prefs", json!({"button":"cancel"})); + + // The state 0.14 and 0.15 saved: the window's body folded. + let mut state = CollapsingState::load_with_default_open(&h.ctx, body, true); + state.set_open(false); + state.store(&h.ctx); + h.call("ui.prefs", json!({"open":"Interface"})); + h.frames(2); + assert!(!folded(&h), "a folded Preferences window unfolds when it opens"); + assert!(crate::scenario::rect_of("prefs:ok").is_some()); + } + + /// Letters typed in the font list's own Search box narrow the list. Preferences' search takes + /// typing only when no text field has the keyboard, so it must not take these. + #[test] + fn typing_in_the_font_lists_search_narrows_the_list_not_the_page() { + use serde_json::json; + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open":"Interface"})); + // Found by searching, as the setting is far down the page. + h.step(&json!({"text": "font"})).expect("search"); + h.frames(3); + let combo = crate::scenario::handle_at("prefs:ui_font").expect("the search finds the font row"); + h.call("ui.click", json!({"x":combo.x,"y":combo.y})); + h.frames(2); + let search = format!("dialog:{} search", crate::i18n::tr("prefs.font")); + let field = crate::scenario::handle_at(&search).expect("the font list is open"); + h.call("ui.click", json!({"x":field.x,"y":field.y})); + h.frames(2); + h.step(&json!({"text": "Comic"})).expect("type"); + h.frames(2); + assert_eq!(h.app.prefs_window.filter, "font", "the Preferences search took the letters"); + assert_eq!(h.app.prefs_window.font_filter, "Comic", "the font list's search keeps them"); + assert!(crate::scenario::handle_at(&search).is_some(), "the font list stays open"); + h.call("ui.prefs", json!({"button":"cancel"})); + } + + #[test] + fn number_fields_take_a_decimal_point_or_a_decimal_comma() { + // #1347 + assert_eq!(super::parse_number("2.5"), Some(2.5)); + assert_eq!(super::parse_number("2,5"), Some(2.5)); + assert_eq!(super::parse_number(" -0,25 "), Some(-0.25)); + assert_eq!(super::parse_number("\u{2212}1,5"), Some(-1.5)); + assert_eq!(super::parse_number("12"), Some(12.0)); + for bad in ["1.234,5", "1,2,3", ",", "abc", "", "inf", "NaN"] { + assert_eq!(super::parse_number(bad), None, "{bad}"); + } + } + + #[test] + fn render_previous_geometry_budget_round_trips_and_resets() { + use serde_json::json; + let mut app = crate::SolveApp::new(Default::default(), Default::default()); + assert!(!app.preferences.render_previous_geometry_budget); + let out = super::set(&mut app, &json!({"render_previous_geometry_budget":true})).unwrap(); + assert_eq!(out["render_previous_geometry_budget"], true); + let mut restored = crate::SolveApp::new(Default::default(), Default::default()); + restored.load_prefs(&app.prefs()); + assert!(restored.preferences.render_previous_geometry_budget); + super::defaults(&mut restored, super::PAGE_GRAPHICS); + assert!(!restored.preferences.render_previous_geometry_budget); + } + + /// Display quality (#1287) is a preference like any other: set by name, checked, saved with + /// the others, back to Normal with Restore Defaults. + #[test] + fn display_quality_is_set_checked_and_restored() { + use serde_json::json; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + assert_eq!(app.preferences.display_quality, "normal"); + let out = super::set(&mut app, &json!({"display_quality": "fine"})).unwrap(); + assert_eq!(out["display_quality"], "fine"); + assert!(super::set(&mut app, &json!({"display_quality": "silky"})).unwrap_err().contains("coarse, normal, fine or ultra")); + assert_eq!(app.preferences.display_quality, "fine"); + assert_eq!(super::lenient(&json!({"display_quality": "ultra"})).display_quality, "ultra"); + super::defaults(&mut app, super::PAGE_GRAPHICS); + assert_eq!(app.preferences.display_quality, "normal"); + } + + #[test] + fn sketch_halo_is_off_by_default_saved_and_restored() { + use serde_json::json; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + assert_eq!(serde_json::to_value(&app.preferences).unwrap()["sketch_halo"], false); + assert_eq!(serde_json::to_value(super::lenient(&json!({}))).unwrap()["sketch_halo"], false); + let saved = super::set(&mut app, &json!({"sketch_halo": true})).unwrap(); + assert_eq!(saved["sketch_halo"], true); + assert_eq!(serde_json::to_value(super::lenient(&saved)).unwrap()["sketch_halo"], true); + super::defaults(&mut app, super::PAGE_GRAPHICS); + assert_eq!(serde_json::to_value(&app.preferences).unwrap()["sketch_halo"], false); + } + + /// Supersampling (#1288): off by default, adaptive, set by factor and checked. + #[test] + fn supersampling_is_off_by_default_and_checked() { + use serde_json::json; + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + assert_eq!((app.preferences.supersampling, app.preferences.supersampling_adaptive), (1.0, true)); + super::set(&mut app, &json!({"supersampling": 2.0})).unwrap(); + assert_eq!(app.preferences.supersampling, 2.0); + assert!(super::set(&mut app, &json!({"supersampling": 3.0})).unwrap_err().contains("1 (off), 1.5 or 2")); + super::set(&mut app, &json!({"supersampling": 1.5, "supersampling_adaptive": false})).unwrap(); + super::defaults(&mut app, super::PAGE_GRAPHICS); + assert_eq!((app.preferences.supersampling, app.preferences.supersampling_adaptive), (1.0, true)); + } + + #[test] + fn a_value_this_version_does_not_understand_keeps_the_other_preferences() { + use serde_json::json; + // A navigator, a field of the wrong type and a key from another release. + let saved = json!({"nav": "solidworks", "navigator_style": "hologram", "ui_scale": "big", "zoom_reverse": true, "from_the_future": 3}); + let p = super::lenient(&saved); + assert_eq!(p.nav, "solidworks"); + assert!(p.zoom_reverse); + assert_eq!(p.navigator_style, super::NavigatorStyle::Axes); + assert_eq!(p.ui_scale, super::Prefs::default().ui_scale); + assert_eq!(super::lenient(&json!("garbage")), super::Prefs::default()); + // Hand-edited toolbar tab lists keep only the tabs each can hold, each once (#5717). + let mut hidden = vec![json!("VIEW"), json!("SHEET METAL"), json!("VIEW"), json!("SURFACE")]; + hidden.extend(std::iter::repeat_n(json!("NOT A TAB"), 10_000)); + let tabs = super::lenient(&json!({"hidden_toolbar_tabs": hidden})); + assert_eq!(tabs.hidden_toolbar_tabs, ["VIEW", "SHEET METAL", "SURFACE"]); + // Whole-app load: the other saved state is kept too, and nothing panics. + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.load_prefs(&json!({"grid": false, "preferences": saved}).to_string()); + assert!(!app.ui.show_grid && app.preferences.nav == "solidworks" && app.preferences.zoom_reverse); + for junk in ["", "{", "[]", "null", "{\"preferences\": 7, \"recent\": {}, \"shortcuts\": 1, \"toolbar\": \"x\"}"] { + crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()).load_prefs(junk); + } + } + + #[test] + fn stored_prefs_fall_back_to_the_legacy_key() { + let only_old = |k: &str| (k == super::LEGACY_STORAGE_KEY).then(|| "old".to_string()); + assert_eq!(super::stored(only_old).as_deref(), Some("old")); + let both = |k: &str| Some(if k == super::STORAGE_KEY { "new" } else { "old" }.to_string()); + assert_eq!(super::stored(both).as_deref(), Some("new")); + assert_eq!(super::stored(|_| None), None); + } + + use super::*; + use crate::navigation::orbit; + + /// Graphics › Window system (#3083): saved in `graphics.json` beside the other start-up + /// settings, refused when unknown, taken back by Cancel; on Linux the pane says which one runs + /// now and, for native Wayland, that some features are limited, with the link. + #[test] + fn the_window_system_is_saved_for_the_next_start() { + use serde_json::json; + let dir = std::env::temp_dir().join(format!("sc_window_system_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("graphics.json"); + std::fs::write(&path, r#"{"msaa":4,"backend":"vulkan"}"#).unwrap(); + let saved = || -> serde_json::Value { serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_default()).unwrap_or_default() }; + let mut h = crate::scenario::Harness::new(); + h.app.services.graphics_path = Some(path.to_string_lossy().to_string()); + h.app.services.window_system = Some("x11"); + assert_eq!(h.app.preferences.window_system, "auto"); + let out = h.call("ui.prefs", json!({"window_system": "wayland"})); + assert_eq!(out["result"]["window_system"], "wayland", "{out}"); + assert_eq!((saved()["window_system"].as_str(), saved()["backend"].as_str()), (Some("wayland"), Some("vulkan")), "the other settings stay"); + assert!(h.call("ui.prefs", json!({"window_system": "mir"}))["error"].as_str().is_some_and(|e| e.contains("window_system"))); + assert_eq!(h.app.preferences.window_system, "wayland", "a refused value changes nothing"); + + h.call("ui.prefs", json!({"open": "Graphics"})); + h.frames(2); + assert_eq!(crate::scenario::handle_at("prefs:window_system").is_some(), cfg!(target_os = "linux"), "the row is on Linux only"); + h.call("ui.prefs", json!({"window_system": "x11"})); + let out = h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(out["result"]["window_system"], "wayland", "Cancel takes the change back"); + assert_eq!(saved()["window_system"], "wayland", "and the file with it"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Preferences › General › Largest file to open (#4086): the defaults are the limits there always + /// were; `ui.prefs` raises both, up to 16 GB and never below the defaults; a saved value out of + /// range reads back in range, and General's Restore Defaults puts them back. + #[test] + fn the_largest_file_to_open_defaults_raises_and_refuses_out_of_range() { + use serde_json::json; + use solidcraft_engine::io::limits::{FileLimits, GB}; + let mut h = crate::scenario::Harness::new(); + assert_eq!((h.app.preferences.max_step_file_mb, h.app.preferences.max_design_file_mb), (512, 256)); + assert_eq!(super::file_limits(&h.app.preferences), FileLimits::DEFAULT); + let out = h.call("ui.prefs", json!({"max_step_file_mb": 4096, "max_design_file_mb": 2048})); + assert_eq!((out["result"]["max_step_file_mb"].as_u64(), out["result"]["max_design_file_mb"].as_u64()), (Some(4096), Some(2048)), "{out}"); + assert_eq!(super::file_limits(&h.app.preferences), FileLimits { step: 4 * GB, design: 2 * GB }); + for bad in [ + json!({"max_step_file_mb": 16385}), + json!({"max_design_file_mb": 100}), + json!({"max_step_file_mb": -1}), + json!({"max_design_file_mb": "2GB"}), + ] { + assert!(h.call("ui.prefs", bad.clone())["error"].is_string(), "{bad}"); + } + assert_eq!(super::file_limits(&h.app.preferences), FileLimits { step: 4 * GB, design: 2 * GB }, "a refused value changes nothing"); + let read = super::lenient(&json!({"max_step_file_mb": 999_999, "max_design_file_mb": 3})); + assert_eq!((read.max_step_file_mb, read.max_design_file_mb), (16384, 256)); + + h.call("ui.prefs", json!({"open": "General"})); + h.frames(2); + super::reveal_preference(&mut h, "prefs:max_step_file_mb"); + assert!(crate::scenario::rect_of("prefs:max_design_file_mb").is_some()); + h.call("ui.prefs", json!({"button": "defaults"})); + assert_eq!(super::file_limits(&h.app.preferences), FileLimits::DEFAULT); + h.call("ui.prefs", json!({"button": "cancel"})); + } + + #[test] + fn graphics_card_picker_selects_named_cards_and_restores_automatic() { + let dir = std::env::temp_dir().join(format!("solidcraft-graphics-picker-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app.services.graphics_path = Some(dir.join("graphics.json").to_string_lossy().into_owned()); + h.app.services.graphics_adapters = vec![("Discrete small".into(), "Discrete small (DiscreteGpu, Vulkan)".into())]; + h.call("ui.prefs", json!({"open":"Graphics"})); + super::reveal_preference(&mut h, "prefs:graphics_card"); + assert!(h.app.preferences.graphics_adapter.is_empty()); + h.step(&json!({"click":{"handle":"prefs:graphics_card"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:graphics_card:0"}})).unwrap(); + assert_eq!(h.app.preferences.graphics_adapter, "Discrete small"); + h.step(&json!({"click":{"handle":"prefs:graphics_card"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:graphics_card:auto"}})).unwrap(); + assert!(h.app.preferences.graphics_adapter.is_empty()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn graphics_card_preference_persists_cancels_and_resets_without_changing_backend() { + let dir = std::env::temp_dir().join(format!("solidcraft-graphics-card-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("graphics.json"); + std::fs::write(&path, r#"{"backend":"vulkan","msaa":4}"#).unwrap(); + let services = crate::Services { graphics_path: Some(path.to_string_lossy().into()), ..Default::default() }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), services); + let snapshot = Snapshot::take(&app); + set(&mut app, &json!({"graphics_adapter":"Discrete large"})).unwrap(); + let read = || serde_json::from_str::(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(read()["adapter"], "Discrete large"); + assert_eq!(read()["backend"], "vulkan"); + let saved = serde_json::to_value(&app.preferences).unwrap(); + assert_eq!(lenient(&saved).graphics_adapter, "Discrete large"); + snapshot.restore(&mut app); + assert_eq!(read()["adapter"], ""); + set(&mut app, &json!({"graphics_adapter":"Discrete small"})).unwrap(); + defaults(&mut app, PAGE_GRAPHICS); + assert_eq!(read()["adapter"], ""); + assert_eq!(read()["backend"], "vulkan"); + assert!(set(&mut app, &json!({"graphics_adapter":"x".repeat(1025)})).is_err()); + assert!(set(&mut app, &json!({"graphics_adapter":"card\nname"})).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn startup_msaa_check_keeps_the_default_unless_fallback_is_confirmed() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.msaa_supported = vec![1, 4, 8]; + for requested in [1, 4, 8] { + app.preferences.msaa = requested; + app.msaa_compatibility = false; + check_msaa(&mut app, requested); + assert_eq!(app.preferences.msaa, requested, "a passing check preserves the choice, including the 4x default"); + assert!(app.settings_reset.is_empty()); + } + app.preferences.msaa = 4; + app.msaa_compatibility = true; + check_msaa(&mut app, 4); + assert_eq!(app.preferences.msaa, 1, "Graphics must show the confirmed fallback so it can be changed back"); + assert!(app.msaa_supported.contains(&4), "the original choice stays available"); + assert!(app.msaa_compatibility, "Graphics explains the fallback"); + assert!(set(&mut app, &serde_json::json!({ "msaa": 4 })).is_ok()); + assert_eq!(app.preferences.msaa, 4); + } + + #[test] + fn unsupported_saved_msaa_is_reset_to_the_default_with_a_notice() { + let dir = std::env::temp_dir().join(format!("sc_msaa_reset_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("graphics.json"); + let services = crate::Services { graphics_path: Some(path.to_string_lossy().to_string()), ..Default::default() }; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), services); + // WebGPU's guarantee for the surface format: 8x saved, the device can only do 1x and 4x. + app.msaa_supported = vec![1, 4]; + app.preferences.msaa = 8; + std::fs::write(&path, r#"{"msaa":8,"backend":"vulkan"}"#).unwrap(); + check_msaa(&mut app, 8); + assert_eq!(app.preferences.msaa, 4); + let saved: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_default()).unwrap_or_default(); + assert_eq!(saved["msaa"], 4); + assert_eq!(saved["backend"], "vulkan", "the backend preference is kept"); + assert_eq!(app.settings_reset, [SettingReset::Msaa { requested: 8, reset: 4, supported: vec![1, 4] }]); + assert_eq!( + app.settings_reset[0].message(), + "Graphics › Anti-aliasing: 8× isn't supported by this graphics device; it is now 4× (supported: 1×, 4×)." + ); + { + let _de = crate::i18n::scope("de"); + assert_eq!( + app.settings_reset[0].message(), + "Grafik › Kantenglättung: 8× wird von diesem Grafikgerät nicht unterstützt; jetzt 4× (unterstützt: 1×, 4×)." + ); + } + // Below the default when the device can't do that either. + app.settings_reset.clear(); + app.msaa_supported = vec![1, 2]; + check_msaa(&mut app, 8); + assert_eq!(app.preferences.msaa, 2); + // Supported, off, or no GPU: nothing changes (OpenGL's 1x policy isn't a reset either). + for (supported, requested) in [(vec![1, 2, 4, 8], 8), (vec![1, 4], 1), (vec![], 8), (vec![1, 4], 4)] { + app.settings_reset.clear(); + app.preferences.msaa = requested; + app.msaa_supported = supported; + check_msaa(&mut app, requested); + assert!(app.settings_reset.is_empty()); + assert_eq!(app.preferences.msaa, requested); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn control_channel_rejects_msaa_the_device_cannot_do_and_bad_saved_msaa_loads_as_default() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.msaa_supported = vec![1, 4]; + assert!(set(&mut app, &serde_json::json!({ "msaa": 8 })).is_err()); + assert!(set(&mut app, &serde_json::json!({ "msaa": 1 })).is_ok()); + app.load_prefs(&serde_json::json!({ "preferences": { "msaa": 16 } }).to_string()); + assert_eq!(app.preferences.msaa, Prefs::default().msaa); + } + + /// "Let AI agents connect" is on for a new install and for preferences saved before it existed; + /// an explicit off stays off. + #[test] + fn agent_control_is_on_unless_saved_off() { + assert!(Prefs::default().agent_control); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.preferences.agent_control = false; + app.load_prefs(&serde_json::json!({ "preferences": { "msaa": 4 } }).to_string()); + assert!(app.preferences.agent_control); + app.load_prefs(&serde_json::json!({ "preferences": { "agent_control": false } }).to_string()); + assert!(!app.preferences.agent_control); + } + + #[test] + fn length_fields_read_bare_numbers_in_design_units_and_honour_explicit_units() { + let inch = unit_scale("in").0; + let close = |a: Option, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-9); + assert!(close(parse_length_mm("2", inch), 50.8)); + assert!(close(parse_length_mm(" 10 mm ", inch), 10.0)); + assert!(close(parse_length_mm("0.5 in", 1.0), 12.7)); + assert!(close(parse_length_mm("1 in + 5 mm", unit_scale("cm").0), 30.4)); + assert!(close(parse_length_mm("3", unit_scale("cm").0), 30.0)); + assert!(close(parse_length_mm("3", 1.0), 3.0)); + assert_eq!(parse_length_mm("10 deg", inch), None); + assert_eq!(parse_length_mm("abc", inch), None); + assert_eq!(parse_length_mm("", inch), None); + assert_eq!(parse_length_mm("1e400", 1.0), None); + } + + #[test] + fn navigator_picker_preserves_axes_and_follows_preferences_transactions() { + let old: Prefs = serde_json::from_value(json!({"nav":"solidworks"})).unwrap(); + assert_eq!(old.navigator_style, NavigatorStyle::Axes); + let mut h = crate::scenario::Harness::new(); + assert!(crate::scenario::handle_at("axis_view:z").is_some()); + assert!(crate::scenario::handle_at("navigation_cube:front").is_none()); + let camera = h.app.cam; + let design = h.app.session.doc.to_json(); + let nav = h.app.preferences.nav.clone(); + h.call("ui.prefs", json!({"open":"Navigation"})); + super::reveal_preference(&mut h, "prefs:navigator"); + let picker = crate::scenario::rect_of("prefs:navigator").unwrap().center(); + h.call("ui.click", json!({"x":picker.x,"y":picker.y})); + let cube = crate::scenario::rect_of("prefs:navigator:Cube").unwrap().center(); + assert!(crate::scenario::rect_of("prefs:navigator:Signed axes").is_some()); + h.call("ui.click", json!({"x":cube.x,"y":cube.y})); + assert_eq!(h.app.preferences.navigator_style, NavigatorStyle::Cube); + assert!(crate::scenario::handle_at("navigation_cube:front").is_some()); + assert_eq!(h.app.preferences.nav, nav); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), design); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.navigator_style, NavigatorStyle::Cube); + let before = h.app.preferences.clone(); + assert!(control(&mut h.app, &json!({"navigator_style":"unknown", "nav":"solidworks"})).is_err()); + assert_eq!(h.app.preferences, before, "invalid settings must fail atomically"); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.navigator_style, NavigatorStyle::Axes); + assert!(crate::scenario::handle_at("navigation_cube:front").is_none()); + h.call("ui.prefs", json!({"open":"Navigation","navigator_style":"cube"})); + h.call("ui.prefs", json!({"button":"apply"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert_eq!(h.app.preferences.navigator_style, NavigatorStyle::Axes); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.navigator_style, NavigatorStyle::Cube); + h.call("ui.prefs", json!({"navigator_style":"axes", "look_at_anim":false})); + h.call("ui.view", json!({"view":"front"})); + let axis = crate::scenario::handle_at("axis_view:-y").unwrap(); + h.call("ui.click", json!({"x":axis.x,"y":axis.y})); + assert!(h.app.cam.back().dist(Vec3::Y) < 1e-6, "original axes retain click-again reversal"); + assert_eq!(h.app.session.doc.to_json(), design); + } + + /// The texts one frame paints. + fn painted_texts(h: &mut crate::scenario::Harness) -> Vec { + let output = h.ctx.run_ui(egui::RawInput { screen_rect: Some(h.ctx.content_rect()), focused: true, ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.job.text.clone()), + _ => None, + }) + .collect() + } + + /// The Interface page's tab colour strip names each tab as the ribbon does, in every language. + #[test] + fn tab_accent_strip_names_the_tabs_as_the_ribbon_does() { + use crate::workspace::tab_name; + fn texts(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let h = crate::scenario::Harness::new(); + for (lang, want) in [ + ("en", ["Model", "Surface", "Mesh", "Form", "Sheet Metal", "Render"]), + ("de", ["Modell", "Fläche", "Mesh", "Form", "Blech", "Rendern"]), + ("fr", ["Modèle", "Surface", "Maillage", "Forme", "Tôlerie", "Rendu"]), + ] { + let _scope = crate::i18n::scope(lang); + let got = ["MODEL", "SURFACE", "MESH", "FORM", "SHEET METAL", "RENDER"].map(tab_name); + assert_eq!(got, want, "{lang}"); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 200.0)); + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::ui_kit::scope(ui, crate::ui_kit::tab_accent_strip); + }); + out.textures_delta.clear(); + let mut painted = Vec::new(); + out.shapes.iter().for_each(|shape| texts(&shape.shape, &mut painted)); + for name in want { + assert!(painted.iter().any(|p| p == name), "{lang}: the strip paints {painted:?}, not {name}"); + } + } + } + + /// Origin plane names (#6491): Top, Front and Right are names shown in the browser, the + /// dialogs' chips and the plane choices; the planes' ids, the commands and the design keep XY, + /// XZ and YZ. Saved, refused when unknown, and taken back by Cancel and Restore Defaults. + #[test] + fn origin_plane_names_change_only_the_names_shown() { + use OriginPlaneNames::{TopFrontRight, Xyz}; + let old: Prefs = serde_json::from_value(json!({"nav":"solidworks"})).unwrap(); + assert_eq!(old.origin_plane_names, Xyz, "older preferences keep XY, XZ and YZ"); + assert_eq!(lenient(&json!({"origin_plane_names":"hologram","zoom_reverse":true})).origin_plane_names, Xyz); + assert_eq!(OriginPlaneNames::PLANES.map(|p| Xyz.label(p)), ["XY", "XZ", "YZ"]); + assert_eq!(OriginPlaneNames::PLANES.map(|p| TopFrontRight.label(p)), ["Top", "Front", "Right"]); + assert_eq!(TopFrontRight.label("Plane1"), "Plane1", "construction planes keep their own names"); + + let mut h = crate::scenario::Harness::new(); + let sketch = h.app.run("sketch.create", json!({"plane":"XY"})).unwrap()["sketch"].as_u64().unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[20,10]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"chevron":"Origin"}})).unwrap(); + let rows = || crate::browser::drawn_rows().into_iter().map(|(label, ..)| label).collect::>(); + assert!(OriginPlaneNames::PLANES.iter().all(|p| rows().iter().any(|r| r == p)), "{:?}", rows()); + let design = h.app.session.doc.to_json(); + h.call("ui.prefs", json!({"open":"Interface"})); + super::reveal_preference(&mut h, "prefs:origin_plane_names:top_front_right"); + h.step(&json!({"click":{"handle":"prefs:origin_plane_names:top_front_right"}})).unwrap(); + assert_eq!(h.app.preferences.origin_plane_names, TopFrontRight); + h.call("ui.prefs", json!({"button":"ok"})); + h.frames(2); + for (id, name) in [("XY", "Top"), ("XZ", "Front"), ("YZ", "Right")] { + assert!(rows().iter().any(|r| r == name) && !rows().iter().any(|r| r == id), "{:?}", rows()); + } + assert_eq!(h.app.session.doc.to_json(), design, "a name shown changes nothing in the design"); + + // Picked from its row, the plane is named in the dialog's chip and runs by its id. + h.call("ui.start", json!({"command":"construct.plane.offset"})); + h.step(&json!({"click":{"browser":"Front"}})).unwrap(); + let picked = h.app.dialog.as_ref().and_then(|d| d.inputs.first()).map(|i| i.items.clone()); + assert_eq!(picked, Some(vec![solidcraft_engine::Sel::Plane { name: "XZ".into() }])); + assert!(painted_texts(&mut h).iter().any(|t| t == "Front"), "the chip shows the plane's name"); + h.step(&json!({"widget":"OK"})).unwrap(); + h.frames(2); + let made = h.app.session.doc.features.last().map(|f| serde_json::to_value(&f.kind).unwrap_or_default()).unwrap_or_default(); + assert!(made.to_string().contains("\"XZ\""), "the command took the id: {made}"); + // The sketch plane choices of Redefine Sketch Plane: by name, and they run by id. + crate::browser::redefine_sketch(&mut h.app, sketch); + h.frames(2); + let texts = painted_texts(&mut h); + assert!(["Use Top plane", "Use Front plane", "Use Right plane"].iter().all(|t| texts.iter().any(|x| x == t)), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Use XY plane")); + crate::sketch_attachment_ui::clear(&mut h.app); + + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.origin_plane_names, TopFrontRight, "the choice is saved"); + let before = h.app.preferences.clone(); + assert!(control(&mut h.app, &json!({"origin_plane_names":"top", "nav":"solidworks"})).is_err()); + assert_eq!(h.app.preferences, before, "an unknown naming fails atomically"); + h.call("ui.prefs", json!({"open":"Interface","origin_plane_names":"xyz"})); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.origin_plane_names, TopFrontRight, "Cancel takes it back"); + h.call("ui.prefs", json!({"open":"Interface"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert_eq!(h.app.preferences.origin_plane_names, Xyz, "Restore Defaults: XY, XZ and YZ"); + h.frames(2); + assert!(OriginPlaneNames::PLANES.iter().all(|p| rows().iter().any(|r| r == p)), "{:?}", rows()); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.origin_plane_names, TopFrontRight); + } + + /// The snap-suppress choice and Direct interaction read in the user's language: the classic + /// choice's "or" was English in every language, and Direct interaction had no message. + #[test] + fn modifier_choice_and_direct_interaction_are_translated() { + let _japanese = crate::i18n::scope("ja"); + let either = crate::tool_modifiers::ModifierCombo::CTRL_ALT.shown_label(); + assert!(either.contains(" または ") && !either.contains(" or "), "{either}"); + assert_ne!(crate::tool_modifiers::ModifierCombo::NONE.shown_label(), "None"); + for english in [ + "Direct interaction", + "Work on the model directly in the viewport. Press a flat face or a profile and pull: up extrudes, down into a body cuts, and sideways movement sets the step size", + ] { + assert_ne!(crate::i18n::tr_label(english), english); + } + } + + #[test] + fn history_sketches_defaults_in_order_and_follows_preferences_transactions() { + let old: Prefs = serde_json::from_value(json!({"timeline_left": true})).unwrap(); + assert_eq!(old.history_sketches, HistorySketches::InOrder, "designs and settings from before keep the creation order"); + assert_eq!(lenient(&json!({"history_sketches": "sideways"})).history_sketches, HistorySketches::InOrder); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"timeline_left": true, "timeline_under_browser": true})); + let design = h.app.session.doc.to_json(); + h.call("ui.prefs", json!({"open": "Interface"})); + let row = h.app.tr("prefs.history_sketches").to_string(); + let under = h.app.tr("prefs.history_sketches_under_feature").to_string(); + let handle = format!("dialog:{row}:{under}"); + super::reveal_preference(&mut h, &handle); + let at = crate::scenario::handle_at(&handle).unwrap(); + h.call("ui.click", json!({"x": at.x, "y": at.y})); + assert_eq!(h.app.preferences.history_sketches, HistorySketches::UnderFeature); + assert_eq!(h.app.session.doc.to_json(), design, "the preference changes only the History"); + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.history_sketches, HistorySketches::InOrder); + + let reply = h.call("ui.prefs", json!({"history_sketches": "under_feature"})); + assert_eq!(reply["result"]["history_sketches"], "under_feature"); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.history_sketches, HistorySketches::UnderFeature); + let before = h.app.preferences.clone(); + assert!(control(&mut h.app, &json!({"history_sketches": "sideways"})).is_err()); + assert_eq!(h.app.preferences, before, "an unknown value changes nothing"); + h.call("ui.prefs", json!({"open": "Interface"})); + h.call("ui.prefs", json!({"button": "defaults"})); + assert_eq!(h.app.preferences.history_sketches, HistorySketches::InOrder); + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.history_sketches, HistorySketches::UnderFeature); + } + + #[test] + fn dialog_buttons_default_bottom_and_follow_preferences_transactions() { + use crate::ui_kit::DialogButtons; + let old: Prefs = serde_json::from_value(json!({"ribbon_labels": false})).unwrap(); + assert_eq!(old.dialog_buttons, DialogButtons::Bottom, "settings from before keep the footer"); + assert_eq!(lenient(&json!({"dialog_buttons": "sideways"})).dialog_buttons, DialogButtons::Bottom); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open": "Interface"})); + super::reveal_preference(&mut h, "prefs:dialog_buttons:top"); + h.step(&json!({"click": {"handle": "prefs:dialog_buttons:top"}})).unwrap(); + assert_eq!(h.app.preferences.dialog_buttons, DialogButtons::Top); + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.dialog_buttons, DialogButtons::Bottom); + + let reply = h.call("ui.prefs", json!({"dialog_buttons": "top"})); + assert_eq!(reply["result"]["dialog_buttons"], "top"); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert_eq!(restored.preferences.dialog_buttons, DialogButtons::Top); + let before = h.app.preferences.clone(); + assert!(control(&mut h.app, &json!({"dialog_buttons": "sideways"})).is_err()); + assert_eq!(h.app.preferences, before, "an unknown value changes nothing"); + h.call("ui.prefs", json!({"open": "Interface"})); + h.call("ui.prefs", json!({"button": "defaults"})); + assert_eq!(h.app.preferences.dialog_buttons, DialogButtons::Bottom); + h.call("ui.prefs", json!({"button": "cancel"})); + assert_eq!(h.app.preferences.dialog_buttons, DialogButtons::Top); + } + + #[test] + fn free_orbit_defaults_off_and_follows_preferences_transactions() { + let old: Prefs = serde_json::from_value(json!({"nav":"solidworks"})).unwrap(); + assert!(!old.free_orbit); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open":"Navigation"})); + h.step(&json!({"click":{"handle":"prefs:free_orbit"}})).unwrap(); + assert!(h.app.preferences.free_orbit); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.free_orbit); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(!h.app.preferences.free_orbit); + h.call("ui.prefs", json!({"open":"Navigation","free_orbit":true,"button":"apply"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(!h.app.preferences.free_orbit); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(h.app.preferences.free_orbit); + } + + #[test] + fn radial_context_menu_defaults_off_and_follows_preferences_transactions() { + assert!(!Prefs::default().radial_context_menu); + let old: Prefs = serde_json::from_value(json!({"nav":"solidworks","zoom_reverse":true})).unwrap(); + assert!(!old.radial_context_menu && old.zoom_reverse && old.nav == "solidworks"); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open":"Navigation"})); + for _ in 0..16 { + let page = crate::scenario::rect_of("dialog:page_body").expect("Navigation page body"); + if h.widget("Radial context menu").is_some_and(|[x, y]| page.contains(egui::pos2(x as f32, y as f32))) { + break; + } + h.call("ui.scroll", json!({"x":page.center().x,"y":page.center().y,"delta":-100})); + h.frames(20); + } + h.step(&json!({"widget":"Radial context menu"})).unwrap(); + assert!(h.app.preferences.radial_context_menu, "the actual checkbox enables radial menus"); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.radial_context_menu, "enabled preference survives save/load"); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(!h.app.preferences.radial_context_menu, "Cancel restores the default-off setting"); + h.call("ui.prefs", json!({"open":"Navigation","radial_context_menu":true})); + h.call("ui.prefs", json!({"button":"apply"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(!h.app.preferences.radial_context_menu, "Navigation defaults disable the ring"); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(h.app.preferences.radial_context_menu, "Cancel restores the last Apply"); + } + + #[test] + fn cosmetic_threads_default_off_and_follow_preferences_transactions() { + assert!(!Prefs::default().cosmetic_threads); + let old: Prefs = serde_json::from_value(json!({"theme":"light","msaa":4})).unwrap(); + assert!(!old.cosmetic_threads && old.theme == "light" && old.msaa == 4); + let malformed = lenient(&json!({"cosmetic_threads":"yes","theme":"light"})); + assert!(!malformed.cosmetic_threads && malformed.theme == "light"); + let mut h = crate::scenario::Harness::new(); + let design = h.app.session.doc.to_json(); + h.call("ui.prefs", json!({"open":"Graphics"})); + super::reveal_preference(&mut h, "prefs:cosmetic_threads"); + let checkbox = crate::scenario::handle_at("prefs:cosmetic_threads").unwrap(); + h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y})); + assert!(h.app.preferences.cosmetic_threads, "the actual checkbox enables the optional markings"); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.cosmetic_threads, "the preference survives saved application settings"); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(!h.app.preferences.cosmetic_threads); + h.call("ui.prefs", json!({"open":"Graphics","cosmetic_threads":true,"button":"apply"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(!h.app.preferences.cosmetic_threads, "Graphics defaults restore the default-off policy"); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(h.app.preferences.cosmetic_threads, "Cancel restores the last Apply"); + h.call("ui.prefs", json!({"cosmetic_threads":false})); + restored.load_prefs(&h.app.prefs()); + assert!(!restored.preferences.cosmetic_threads, "an explicitly disabled value also survives reload"); + assert_eq!(h.app.session.doc.to_json(), design); + assert!(h.app.session.undo.is_empty()); + } + + #[test] + fn tool_modifier_prefs_default_classic_and_persist() { + let d = Prefs::default(); + assert_eq!(d.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(d.manipulator_free_alt); + assert!(!d.selection_shift_add_only); + let old: Prefs = serde_json::from_value(json!({"nav": "solidworks"})).unwrap(); + assert_eq!(old.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(!old.selection_shift_add_only); + // Classic default: Ctrl/Cmd or Alt each suppress (`command` is primary on all hosts). + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let ctrl = Modifiers { ctrl: true, command: true, ..Default::default() }; + let alt = Modifiers { alt: true, ..Default::default() }; + let shift = Modifiers { shift: true, ..Default::default() }; + assert!(suppress_sketch_snap_held(&app, ctrl)); + assert!(suppress_sketch_snap_held(&app, alt)); + assert!(!suppress_sketch_snap_held(&app, shift)); + control( + &mut app, + &json!({"open": "Sketch", "suppress_sketch_snap": {"shift": false, "ctrl": true, "alt": false}, "manipulator_free_alt": false}), + ) + .unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + control(&mut app, &json!({"open": "Selection", "selection_shift_add_only": true})).unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + assert!(!app.preferences.manipulator_free_alt); + assert!(app.preferences.selection_shift_add_only); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + assert!(!other.preferences.manipulator_free_alt); + assert!(other.preferences.selection_shift_add_only); + control(&mut app, &json!({"open": "Sketch", "button": "defaults"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL_ALT); + assert!(app.preferences.manipulator_free_alt); + assert!(!app.preferences.selection_shift_add_only, "the merged Sketch & selection page resets both sets of modifiers"); + control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!(app.preferences.suppress_sketch_snap, ModifierCombo::CTRL); + } + + #[test] + fn wheel_smoothing_persists_and_follows_dialog_buttons() { + assert!(serde_json::from_value::(json!({})).unwrap().smooth_wheel_zoom); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + control(&mut app, &json!({"open":"Navigation", "smooth_wheel_zoom":false})).unwrap(); + control(&mut app, &json!({"button":"cancel"})).unwrap(); + assert!(app.preferences.smooth_wheel_zoom); + control(&mut app, &json!({"open":"Navigation", "smooth_wheel_zoom":false})).unwrap(); + control(&mut app, &json!({"button":"apply"})).unwrap(); + control(&mut app, &json!({"smooth_wheel_zoom":true, "button":"cancel"})).unwrap(); + assert!(!app.preferences.smooth_wheel_zoom); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert!(!other.preferences.smooth_wheel_zoom); + control(&mut app, &json!({"open":"Navigation", "button":"defaults"})).unwrap(); + assert!(app.preferences.smooth_wheel_zoom); + control(&mut app, &json!({"button":"cancel"})).unwrap(); + assert!(!app.preferences.smooth_wheel_zoom); + } + + #[test] + fn touchpad_preset_persists_and_obeys_preference_transactions() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + control(&mut app, &json!({"open":"Navigation", "nav":"touchpad"})).unwrap(); + assert_eq!(app.preferences.nav, "touchpad"); + assert!(app.preferences.trackpad_pan, "choosing Touchpad must not overwrite the saved scroll preference"); + control(&mut app, &json!({"button":"cancel"})).unwrap(); + assert_eq!(app.preferences.nav, "fusion"); + control(&mut app, &json!({"open":"Navigation", "nav":"touchpad", "button":"apply"})).unwrap(); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.nav, "touchpad"); + control(&mut app, &json!({"button":"defaults"})).unwrap(); + assert_eq!(app.preferences.nav, "fusion"); + control(&mut app, &json!({"button":"cancel"})).unwrap(); + assert_eq!(app.preferences.nav, "touchpad"); + } + + #[test] + fn choosing_the_solidworks_preset_frees_the_right_button_and_fits_on_middle_double_click() { + let none = Modifiers::default(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.preferences.middle_double_click = "off".into(); + set(&mut app, &json!({"nav": "solidworks"})).unwrap(); + assert!(app.preferences.right_drag_orbits, "a saved SolidWorks preset keeps its right-drag orbit"); + assert_eq!(nav_mode(&app, NavButton::Right, none), Some(NavMode::Orbit)); + choose_nav_preset(&mut app.preferences, nav_preset("fusion")); + let p = &app.preferences; + assert_eq!((p.nav.as_str(), p.zoom_reverse, p.middle_double_click.as_str(), p.right_drag_orbits), ("fusion", false, "off", true)); + choose_nav_preset(&mut app.preferences, nav_preset("solidworks")); + let p = &app.preferences; + assert_eq!((p.nav.as_str(), p.zoom_reverse, p.middle_double_click.as_str(), p.right_drag_orbits), ("solidworks", true, "fit", false)); + assert_eq!(nav_mode(&app, NavButton::Right, none), None, "right drag is left to the context menu (#6492)"); + assert_eq!(nav_mode(&app, NavButton::Middle, none), Some(NavMode::Orbit)); + set(&mut app, &json!({"nav": "openscad"})).unwrap(); + assert_eq!(nav_mode(&app, NavButton::Right, none), Some(NavMode::Pan), "only an orbiting right drag is affected"); + set(&mut app, &json!({"right_drag_orbits": true, "nav": "solidworks"})).unwrap(); + assert_eq!(nav_mode(&app, NavButton::Right, none), Some(NavMode::Orbit), "turned back on, the right drag orbits again"); + } + + #[test] + fn openscad_preset_maps_navigation_and_persists() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + set(&mut app, &json!({"nav": OPENSCAD_NAV})).unwrap(); + for button in [NavButton::Middle, NavButton::Right] { + assert_eq!(nav_mode(&app, button, Modifiers::default()), Some(NavMode::Pan)); + assert_eq!(nav_mode(&app, button, Modifiers { shift: true, ..Default::default() }), Some(NavMode::Zoom)); + } + assert_eq!(nav_mode(&app, NavButton::Left, Modifiers::default()), Some(NavMode::Orbit)); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.nav, OPENSCAD_NAV); + } + + #[test] + fn pan_reverse_x_defaults_off_persists_and_flips_the_sign() { + assert!(!serde_json::from_value::(json!({})).unwrap().pan_reverse_x); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert_eq!(pan_sign_x(&app), 1.0); + set(&mut app, &json!({"pan_reverse_x": true})).unwrap(); + assert_eq!(pan_sign_x(&app), -1.0); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert!(other.preferences.pan_reverse_x); + } + + #[test] + fn orbit_reverse_defaults_off_persists_and_flips_the_sign() { + assert!(!serde_json::from_value::(json!({})).unwrap().orbit_reverse); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert_eq!(orbit_sign(&app), 1.0); + set(&mut app, &json!({"orbit_reverse": true})).unwrap(); + assert_eq!(orbit_sign(&app), -1.0); + assert_eq!((pan_sign_x(&app), pan_sign_y(&app)), (1.0, 1.0)); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert!(other.preferences.orbit_reverse); + } + + #[test] + fn pan_reverse_y_defaults_off_persists_and_flips_the_sign() { + assert!(!serde_json::from_value::(json!({})).unwrap().pan_reverse_y); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert_eq!(pan_sign_y(&app), 1.0); + set(&mut app, &json!({"pan_reverse_y": true})).unwrap(); + assert_eq!(pan_sign_y(&app), -1.0); + assert_eq!(pan_sign_x(&app), 1.0); + set(&mut app, &json!({"pan_reverse_x": true, "pan_reverse_y": false})).unwrap(); + assert_eq!(pan_sign_x(&app), -1.0); + assert_eq!(pan_sign_y(&app), 1.0); + set(&mut app, &json!({"pan_reverse_y": true})).unwrap(); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert!(other.preferences.pan_reverse_y); + } + + #[test] + fn trackpad_pan_defaults_on_persists_and_follows_dialog_buttons() { + assert!(serde_json::from_value::(json!({})).unwrap().trackpad_pan); + assert!(Prefs::default().trackpad_pan); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + control(&mut app, &json!({"open":"Navigation", "trackpad_pan":false})).unwrap(); + control(&mut app, &json!({"button":"cancel"})).unwrap(); + assert!(app.preferences.trackpad_pan); + control(&mut app, &json!({"open":"Navigation", "trackpad_pan":false})).unwrap(); + control(&mut app, &json!({"button":"apply"})).unwrap(); + assert!(!app.preferences.trackpad_pan); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert!(!other.preferences.trackpad_pan); + control(&mut app, &json!({"open":"Navigation", "button":"defaults"})).unwrap(); + assert!(app.preferences.trackpad_pan); + control(&mut app, &json!({"button":"cancel"})).unwrap(); + assert!(!app.preferences.trackpad_pan); + } + + #[test] + fn blender_preset_moves_the_camera_with_the_middle_button_only() { + // #1090: orbit, pan and zoom all on the middle button; no left or right drag binding, so + // those stay selection and the context menu (Ctrl+left on empty space orbits in every + // preset, outside the bindings). + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + set(&mut app, &json!({"nav": "blender"})).unwrap(); + let none = Modifiers::default(); + let shift = Modifiers { shift: true, ..Default::default() }; + let ctrl = Modifiers { ctrl: true, ..Default::default() }; + assert_eq!(nav_mode(&app, NavButton::Middle, none), Some(NavMode::Orbit)); + assert_eq!(nav_mode(&app, NavButton::Middle, shift), Some(NavMode::Pan)); + assert_eq!(nav_mode(&app, NavButton::Middle, ctrl), Some(NavMode::Zoom)); + for mods in [none, shift, ctrl] { + assert_eq!(nav_mode(&app, NavButton::Left, mods), None); + assert_eq!(nav_mode(&app, NavButton::Right, mods), None); + } + assert_eq!(zoom_sign(&app), 1.0, "the wheel turns the usual way"); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.nav, "blender"); + } + + #[test] + fn presets_map_the_mouse_and_prefs_round_trip() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let shift = Modifiers { shift: true, ..Default::default() }; + let ctrl = Modifiers { ctrl: true, ..Default::default() }; + let none = Modifiers::default(); + assert!(matches!(nav_mode(&app, NavButton::Middle, none), Some(NavMode::Pan))); + assert!(matches!(nav_mode(&app, NavButton::Middle, shift), Some(NavMode::Orbit))); + set(&mut app, &json!({"nav": "solidworks"})).unwrap(); + assert!(matches!(nav_mode(&app, NavButton::Middle, none), Some(NavMode::Orbit))); + assert!(matches!(nav_mode(&app, NavButton::Middle, ctrl), Some(NavMode::Pan))); + set(&mut app, &json!({"nav": "inventor", "zoom_reverse": true})).unwrap(); + assert!(matches!(nav_mode(&app, NavButton::Middle, ctrl), Some(NavMode::Zoom))); + assert_eq!(zoom_sign(&app), -1.0); + assert!(matches!(nav_mode(&app, NavButton::Right, none), Some(NavMode::Orbit)), "right drag orbits everywhere"); + assert_eq!(nav_mode(&app, NavButton::Left, none), None, "left drag selects"); + let shift_alt = Modifiers { shift: true, alt: true, ..Default::default() }; + assert_eq!(nav_mode(&app, NavButton::Left, shift_alt), None, "only Alias navigates with the left button"); + set(&mut app, &json!({"nav": "alias"})).unwrap(); + assert_eq!(nav_mode(&app, NavButton::Left, shift_alt), Some(NavMode::Orbit)); + assert_eq!(nav_mode(&app, NavButton::Middle, shift_alt), Some(NavMode::Pan)); + assert_eq!(nav_mode(&app, NavButton::Right, shift_alt), Some(NavMode::Zoom)); + assert_eq!(nav_mode(&app, NavButton::Left, none), None, "a plain left drag still selects"); + assert_eq!(nav_mode(&app, NavButton::Left, shift), None); + assert_eq!(nav_mode(&app, NavButton::Right, none), Some(NavMode::Orbit)); + assert!(set(&mut app, &json!({"nav": "no-such-preset"})).is_err()); + assert!(set(&mut app, &json!({"default_units": "furlong"})).is_err()); + assert!(set(&mut app, &json!({"nope": 1})).is_err()); + // Kept between runs. + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences, app.preferences); + assert_eq!(format_length(25.4, "in", 3), "1.000 in"); + } + + /// #6474, #2742: Maya moves the camera with Alt and any button, HFSS with Alt or Shift+Alt and + /// the left button. A plain left drag still selects, and HFSS leaves Ctrl+left to the drag + /// from empty space every preset has, so a Ctrl+click on geometry still adds to the selection. + #[test] + fn maya_and_hfss_presets_navigate_with_alt() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let none = Modifiers::default(); + let alt = Modifiers { alt: true, ..Default::default() }; + let shift_alt = Modifiers { shift: true, alt: true, ..Default::default() }; + let ctrl = Modifiers { ctrl: true, ..Default::default() }; + set(&mut app, &json!({"nav": "maya"})).unwrap(); + assert_eq!(nav_mode(&app, NavButton::Left, alt), Some(NavMode::Orbit)); + assert_eq!(nav_mode(&app, NavButton::Middle, alt), Some(NavMode::Pan)); + assert_eq!(nav_mode(&app, NavButton::Right, alt), Some(NavMode::Zoom)); + assert_eq!(nav_mode(&app, NavButton::Middle, none), Some(NavMode::Pan)); + assert_eq!(nav_mode(&app, NavButton::Left, none), None, "a plain left drag selects"); + assert_eq!(nav_mode(&app, NavButton::Right, none), None, "a plain right click opens the context menu"); + set(&mut app, &json!({"nav": "hfss"})).unwrap(); + assert_eq!(nav_mode(&app, NavButton::Left, alt), Some(NavMode::Pan)); + assert_eq!(nav_mode(&app, NavButton::Left, shift_alt), Some(NavMode::Zoom)); + assert_eq!(nav_mode(&app, NavButton::Left, none), None); + assert_eq!(nav_mode(&app, NavButton::Left, ctrl), None); + assert_eq!(zoom_sign(&app), 1.0); + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.nav, "hfss"); + } + + /// The dialog: changes apply at once, Cancel puts back what was there when it opened, Apply + /// keeps them, Restore Defaults resets one page, and the shortcuts menus open its page. + #[test] + fn preferences_dialog_cancel_apply_and_defaults() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + control(&mut app, &json!({"open": "general"})).unwrap(); + assert!(app.prefs_window.open && app.prefs_window.section == 0); + control(&mut app, &json!({"theme": "light", "ui_scale": 1.25, "zoom_to_cursor": false})).unwrap(); + assert!(!app.ui.dark, "light applies at once"); + app.keymap.custom.insert("solid.extrude".into(), vec!["Shift+E".into()]); + let v = control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!(v["dialog"], serde_json::Value::Null); + assert!(app.ui.dark && app.preferences.theme == "dark" && app.preferences.ui_scale == 1.0 && app.preferences.zoom_to_cursor); + assert!(app.keymap.custom.is_empty(), "a rebinding made while the dialog was open is undone too"); + + control(&mut app, &json!({"open": "Navigation", "nav": "alias", "look_at_anim": false})).unwrap(); + control(&mut app, &json!({"button": "apply"})).unwrap(); + control(&mut app, &json!({"nav": "tinkercad"})).unwrap(); + control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!(app.preferences.nav, "alias", "Cancel goes back to the last Apply"); + let to = { + let mut c = app.cam; + c.set_view(solidcraft_engine::render::StandardView::Top); + c + }; + app.animate_to(to); + assert!(app.cam_anim.is_none() && app.cam == to, "no animation: the view jumps"); + + control(&mut app, &json!({"open": "Navigation"})).unwrap(); + control(&mut app, &json!({"button": "defaults"})).unwrap(); + assert_eq!(app.preferences.nav, "fusion"); + assert!(app.preferences.look_at_anim); + control(&mut app, &json!({"button": "ok"})).unwrap(); + assert!(!app.prefs_window.open); + + // File and Help › Keyboard Shortcuts open the same dialog at its page. + app.keymap.open = true; + let ctx = crate::fonts::test_context(); + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.prefs_window.open && app.prefs_window.section == PAGE_SHORTCUTS && !app.keymap.open); + assert!(control(&mut app, &json!({"open": "NoSuch"})).is_err()); + assert!(set(&mut app, &json!({"up_axis": "x"})).is_err()); + assert!(set(&mut app, &json!({"theme": "sepia"})).is_err()); + assert!(set(&mut app, &json!({"language": "xx"})).is_err()); + } + + /// Apply is disabled while nothing changed since the dialog opened or since the last Apply, + /// enabled by a change, and disabled again by Apply (#8561). + #[test] + fn apply_is_enabled_only_while_something_changed() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let ctx = crate::fonts::test_context(); + let input = || egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let draw = |app: &mut SolveApp, events: Vec| { + crate::test_support::frame(&ctx, egui::RawInput { events, ..input() }, |ui| show(app, ui.ctx())); + crate::scenario::count_of("dialog:apply:enabled") + }; + let v = control(&mut app, &json!({"open": "Navigation"})).unwrap(); + assert_eq!(v["apply_enabled"], false, "nothing changed yet"); + assert_eq!(draw(&mut app, vec![]), Some(0.0), "just opened: Apply is disabled"); + + let v = control(&mut app, &json!({"zoom_to_cursor": false})).unwrap(); + assert_eq!(v["apply_enabled"], true); + assert_eq!(draw(&mut app, vec![]), Some(1.0), "after a change: Apply is enabled"); + let v = control(&mut app, &json!({"zoom_to_cursor": true})).unwrap(); + assert_eq!(v["apply_enabled"], false, "a change put back by hand leaves nothing to apply"); + control(&mut app, &json!({"zoom_to_cursor": false})).unwrap(); + + // Clicking Apply keeps the change and leaves nothing to apply. + draw(&mut app, vec![]); + let apply = crate::scenario::handle_at("dialog:apply").unwrap(); + draw(&mut app, crate::test_support::pointer(apply, true)); + draw(&mut app, crate::test_support::pointer(apply, false)); + assert!(app.prefs_window.open && !app.preferences.zoom_to_cursor, "Apply keeps the dialog and the change"); + assert_eq!(draw(&mut app, vec![]), Some(0.0), "after Apply: Apply is disabled"); + // A disabled Apply does nothing when clicked. + draw(&mut app, crate::test_support::pointer(apply, true)); + draw(&mut app, crate::test_support::pointer(apply, false)); + assert_eq!(draw(&mut app, vec![]), Some(0.0)); + + // Every setting Cancel would put back counts, the shortcuts and view settings included; + // update bookkeeping (not a setting, and Cancel keeps it) does not. + app.preferences.update.last_check += 1.0; + assert_eq!(draw(&mut app, vec![]), Some(0.0), "update bookkeeping is not a change"); + app.keymap.custom.insert("solid.extrude".into(), vec!["Shift+E".into()]); + assert_eq!(draw(&mut app, vec![]), Some(1.0), "a rebinding is a change"); + let v = control(&mut app, &json!({"button": "apply"})).unwrap(); + assert_eq!(v["apply_enabled"], false); + app.ui.show_grid = !app.ui.show_grid; + assert_eq!(draw(&mut app, vec![]), Some(1.0), "a view setting is a change"); + + // Cancel puts it back and closes; opened again, there is nothing to apply. + let v = control(&mut app, &json!({"button": "cancel"})).unwrap(); + assert_eq!(v["apply_enabled"], false); + let v = control(&mut app, &json!({"open": "General"})).unwrap(); + assert_eq!(v["apply_enabled"], false); + } + + #[test] + fn language_preference_switches_and_persists() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert_eq!(app.preferences.language, "en"); + assert_eq!(app.tr("ui.preferences"), "Preferences"); + assert_eq!(app.tr("ui.extrude"), "Extrude"); + + // Switch language to Japanese + set(&mut app, &json!({"language": "ja", "timeline_left": true})).unwrap(); + app.preferences.timeline_left_browser_collapsed = true; + assert_eq!(app.preferences.language, "ja"); + assert!(app.preferences.timeline_left); + assert_eq!(app.tr("ui.preferences"), "環境設定"); + assert_eq!(app.tr("ui.extrude"), "押し出し"); + + // Preferences round-trip + let mut other = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + other.load_prefs(&app.prefs()); + assert_eq!(other.preferences.language, "ja"); + assert!(other.preferences.timeline_left); + assert!(other.preferences.timeline_left_browser_collapsed); + assert_eq!(other.tr("ui.preferences"), "環境設定"); + } + + /// A STEP file opened Z-up is offered to be stood up: a quarter turn about X, undoable. + #[test] + fn a_y_up_step_file_can_be_stood_up() { + let dir = std::env::temp_dir().join(format!("solidcraft-standup-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("tall_in_y.step").to_string_lossy().to_string(); + let mut src = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + src.run("solid.box", json!({"length": 10, "width": 40, "height": 5})).unwrap(); + src.run("file.export", json!({"path": path})).unwrap(); + + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.open_path(&path); + assert!(app.stand_up.is_none(), "SolidCraft's own exports already have Z up"); + // Another originating system is offered (asked in the dialog, without looking at how the + // flat box rests). + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::write(&path, text.replace("'SolidCraft','SolidCraft'", "'SolidCraft','Example CAD'")).unwrap(); + app.preferences.stand_up_unknown = StandUpUnknown::Ask; + app.open_path(&path); + let offered = app.stand_up.clone().unwrap_or_default(); + assert_eq!(offered.len(), 1, "the file's body is offered"); + let size = |app: &SolveApp| solidcraft_engine::view::bounds(&app.session); + assert!((size(&app).max.y - size(&app).min.y - 40.0).abs() < 1e-6); + control(&mut app, &json!({"stand_up": true})).unwrap(); + let b = size(&app); + assert!((b.max.z - b.min.z - 40.0).abs() < 1e-6, "Y became Z: {b:?}"); + assert!(app.stand_up.is_none()); + app.run("edit.undo", json!({})).unwrap(); + assert!((size(&app).max.y - size(&app).min.y - 40.0).abs() < 1e-6, "one undo step"); + + // Not offered when turned off, or with Y up as the default orientation. + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.preferences.offer_stand_up = false; + app.open_path(&path); + assert!(app.stand_up.is_none()); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.preferences.up_axis = "y".into(); + app.open_path(&path); + assert!(app.stand_up.is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Orbiting about the world origin keeps the origin where it was drawn, even when Pan has + /// moved it off to the side. + #[test] + fn orbiting_around_the_origin_keeps_it_still() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("solid.box", json!({"length": 40, "width": 40, "height": 40})).unwrap(); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + app.fit_view(); + assert_eq!(app.preferences.orbit_around, OrbitAround::ViewCentre, "the view centre stays the default"); + app.preferences.orbit_around = OrbitAround::Origin; + app.cam.pan(60.0, -25.0, 600.0); + let was = (app.cam.yaw, app.cam.pitch); + let before = crate::viewport::projection(&app, rect).to_screen(Vec3::ZERO).unwrap(); + orbit(&mut app, rect, 40.0, 25.0, None); + let after = crate::viewport::projection(&app, rect).to_screen(Vec3::ZERO).unwrap(); + assert!(after.distance(before) < 2.0, "{before:?} -> {after:?}"); + assert_ne!((app.cam.yaw, app.cam.pitch), was, "the view must turn"); + } + + /// Preferences saved before the origin option had `orbit_cursor`: that choice survives, and + /// the control channel still accepts the old key. + #[test] + fn saved_cursor_preference_migrates_to_the_origin_option() { + assert_eq!(lenient(&json!({"orbit_cursor": true})).orbit_around, OrbitAround::Cursor); + assert_eq!(lenient(&json!({"orbit_cursor": false})).orbit_around, OrbitAround::ViewCentre); + assert_eq!(lenient(&json!({})).orbit_around, OrbitAround::ViewCentre); + assert_eq!(lenient(&json!({"orbit_around": "origin"})).orbit_around, OrbitAround::Origin); + + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + set(&mut app, &json!({"orbit_around": "origin"})).unwrap(); + assert_eq!(app.preferences.orbit_around, OrbitAround::Origin); + set(&mut app, &json!({"orbit_cursor": true})).unwrap(); + assert_eq!(app.preferences.orbit_around, OrbitAround::Cursor, "the old key still moves the choice"); + assert!(!app.preferences.orbit_cursor, "and is folded away"); + } + + #[test] + fn the_agent_chat_limit_is_off_unless_chosen() { + assert_eq!(Prefs::default().agent_chat_turn_limit, 0); + assert_eq!(migrate(lenient(&json!({"agent_chat_turn_limit": 24}))).agent_chat_turn_limit, 0, "the old default reads as no limit"); + assert_eq!(lenient(&json!({"agent_chat_turn_limit": 10})).agent_chat_turn_limit, 10); + } + + #[test] + fn orbiting_around_the_cursor_keeps_that_point_still() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("solid.box", json!({"length": 40, "width": 40, "height": 40})).unwrap(); + app.preferences.orbit_around = OrbitAround::Cursor; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + app.fit_view(); + let at = egui::pos2(500.0, 250.0); + let pivot = pivot_under(&app, &crate::viewport::projection(&app, rect), at); + orbit(&mut app, rect, 40.0, 25.0, Some(at)); + let s = crate::viewport::projection(&app, rect).to_screen(pivot).unwrap(); + assert!(s.distance(at) < 2.0, "{s:?}"); + } + + /// A drag that starts on an edge turns around the edge's point under the cursor, not its + /// middle, and that point stays still on screen. + #[test] + fn orbiting_from_an_edge_turns_around_the_point_under_the_cursor() { + use crate::viewport::Hit; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("solid.box", json!({"length": 200, "width": 40, "height": 40})).unwrap(); + app.preferences.orbit_around = OrbitAround::Cursor; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + app.fit_view(); + let proj = crate::viewport::projection(&app, rect); + let st = app.session.world_state(); + let m = st.bodies[0].mesh(); + // A spot a fifth of the way along a visible edge, well away from its middle on screen. + let found = m.edges.iter().filter(|e| e.len() >= 2).find_map(|e| { + let (a, b) = (e[0], e[e.len() - 1]); + let at = proj.to_screen(a + (b - a) * 0.2)?; + let mid = proj.to_screen(crate::viewport::polyline_mid(e))?; + let first = + crate::viewport::pick(&app, &proj, at).into_iter().find(|h| matches!(h, Hit::Face { .. } | Hit::Edge { .. } | Hit::Vertex { .. })); + (rect.contains(at) && at.distance(mid) > 100.0 && matches!(first, Some(Hit::Edge { .. }))).then_some((at, mid)) + }); + let (at, mid) = found.unwrap(); + let pivot = pivot_under(&app, &proj, at); + let on_screen = proj.to_screen(pivot).unwrap(); + assert!(on_screen.distance(at) < 6.0, "the pivot is under the cursor: {on_screen:?} vs {at:?}"); + assert!(on_screen.distance(mid) > 90.0, "not the edge's middle"); + orbit(&mut app, rect, 40.0, 25.0, Some(at)); + assert_eq!(app.viewport.orbit_pivot, Some(pivot)); + let after = crate::viewport::projection(&app, rect).to_screen(pivot).unwrap(); + assert!(after.distance(on_screen) < 2.0, "{on_screen:?} -> {after:?}"); + } + + /// On a sketch line too: the line's point under the cursor, not the view's middle. + #[test] + fn orbiting_from_a_sketch_line_turns_around_the_point_under_the_cursor() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + app.run("sketch.line", json!({"points": [[-100, 0], [100, 0]]})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + app.preferences.orbit_around = OrbitAround::Cursor; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + app.fit_view(); + let proj = crate::viewport::projection(&app, rect); + let on_line = Vec3::new(-60.0, 0.0, 0.0); + let at = proj.to_screen(on_line).unwrap(); + let pivot = pivot_under(&app, &proj, at); + assert!(pivot.dist(on_line) < 2.0, "{pivot:?}"); + } + + /// A drag that starts over empty space turns around the visible geometry's centre, not a + /// point far off to the side; with nothing visible it turns around the view's centre. + #[test] + fn orbiting_from_empty_space_turns_around_the_visible_geometry() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.run("solid.box", json!({"length": 40, "width": 40, "height": 40})).unwrap(); + app.preferences.orbit_around = OrbitAround::Cursor; + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + app.fit_view(); + let corner = egui::pos2(10.0, 10.0); + let proj = crate::viewport::projection(&app, rect); + let hits = crate::viewport::pick(&app, &proj, corner); + use crate::viewport::Hit; + assert!(!hits.iter().any(|h| matches!(h, Hit::Face { .. } | Hit::Edge { .. } | Hit::Vertex { .. })), "the corner is empty space"); + let centre = crate::viewport::view_bounds(&app).center(); + orbit(&mut app, rect, 40.0, 25.0, Some(corner)); + assert_eq!(app.viewport.orbit_pivot, Some(centre)); + + let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.preferences.orbit_around = OrbitAround::Cursor; + app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, -3.0, 2.0); + orbit(&mut app, rect, 40.0, 25.0, Some(corner)); + assert_eq!(app.viewport.orbit_pivot, Some(solidcraft_engine::geom::Vec3::new(5.0, -3.0, 2.0))); + } + + /// The Y up preference turns the view: the camera's up axis follows it, startup included. + #[test] + fn up_axis_preference_turns_the_view() { + use solidcraft_engine::render::UpAxis; + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + let ctx = crate::fonts::test_context(); + apply(&mut app, &ctx); + assert_eq!(app.cam.up, UpAxis::Z); + app.preferences.up_axis = "y".into(); + apply(&mut app, &ctx); + assert_eq!((app.ui.up_axis, app.cam.up), (UpAxis::Y, UpAxis::Y)); + // Home looks at the model with Y up: the eye is above the XZ ground. + assert!(app.cam.back().y > 0.3, "{:?}", app.cam.back()); + app.preferences.up_axis = "z".into(); + apply(&mut app, &ctx); + assert_eq!(app.cam.up, UpAxis::Z); + } +} + +#[cfg(test)] +mod ui_scale_regression_tests { + use super::*; + use egui::{Event, Modifiers, PointerButton, pos2}; + + #[test] + fn desktop_zoom_shortcuts_update_and_persist_the_scale_preference() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.key", json!({"key":"Minus","cmd":true})); + assert!((h.app.preferences.ui_scale - 0.9).abs() < 1e-4); + assert!((h.ctx.zoom_factor() - 0.9).abs() < 1e-4); + h.frames(12); + assert!((h.ctx.zoom_factor() - 0.9).abs() < 1e-4, "must not flash back to the old preference"); + h.step(&json!({"restart":"close"})).unwrap(); + assert!((h.app.preferences.ui_scale - 0.9).abs() < 1e-4); + h.call("ui.key", json!({"key":"Equals","cmd":true})); + assert!((h.ctx.zoom_factor() - 1.0).abs() < 1e-4); + h.call("ui.key", json!({"key":"Plus","cmd":true})); + assert!((h.ctx.zoom_factor() - 1.1).abs() < 1e-4); + h.call("ui.key", json!({"key":"0","cmd":true})); + assert!((h.ctx.zoom_factor() - 1.0).abs() < 1e-4); + h.call("ui.prefs", json!({"ui_scale":0.5})); + h.call("ui.key", json!({"key":"Minus","cmd":true})); + assert_eq!(h.app.preferences.ui_scale, 0.5); + h.call("ui.prefs", json!({"ui_scale":2.5})); + h.call("ui.key", json!({"key":"Plus","cmd":true})); + assert_eq!(h.app.preferences.ui_scale, 2.5); + } + + #[test] + fn dragging_the_scale_slider_keeps_its_window_still_until_release() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open":"Interface"})); + let window = crate::scenario::rect_of("prefs:window").unwrap(); + super::reveal_preference(&mut h, "prefs:scale"); + let slider = crate::scenario::rect_of("prefs:scale").unwrap(); + let a = pos2(slider.left() + 20.0, slider.center().y); + let b = pos2(slider.left() + 90.0, slider.center().y); + h.app.synthetic.push(Event::PointerMoved(a)); + h.app.synthetic.push(Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.frames(3); + h.app.synthetic.push(Event::PointerMoved(b)); + h.frames(4); + assert_ne!(h.app.preferences.ui_scale, 1.0, "the slider changes its value during the drag"); + assert_eq!(h.ctx.zoom_factor(), 1.0, "layout must remain stable until release"); + assert_eq!(crate::scenario::rect_of("prefs:window").unwrap(), window); + h.app.synthetic.push(Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.frames(5); + assert!((h.ctx.zoom_factor() - h.app.preferences.ui_scale).abs() < 1e-4); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(h.app.preferences.ui_scale, 1.0, "Cancel restores the original scale"); + assert_eq!(h.ctx.zoom_factor(), 1.0); + } +} + +/// View ▸ View angles and Preferences ▸ Graphics run the same command (#6032). +pub(crate) fn view_angles_checkbox(app: &mut SolveApp, ui: &mut egui::Ui) { + let mut enabled = app.preferences.show_view_angles; + let response = ui_kit::checkbox(ui, crate::i18n::tr("ui.view_angles"), &mut enabled).on_hover_text(crate::i18n::tr("ui.view_angles_help")); + crate::scenario::publish_handle("view:view_angles", response.rect.center()); + if response.changed() { + let _ = app.run("view.angle_readout", json!({"enabled": enabled})); + } +} + +#[cfg(test)] +mod ambient_occlusion_tests { + use super::*; + + #[test] + fn ambient_occlusion_is_optional_persistent_and_cancelable() { + let old: Prefs = serde_json::from_value(json!({"msaa": 4})).unwrap(); + assert!(!old.ambient_occlusion); + let mut h = crate::scenario::Harness::new(); + let camera = h.app.cam; + let design = h.app.session.doc.to_json(); + h.call("ui.prefs", json!({"open":"Graphics"})); + super::reveal_preference(&mut h, "view:ambient_occlusion"); + let checkbox = crate::scenario::handle_at("view:ambient_occlusion").unwrap(); + h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y})); + assert!(h.app.preferences.ambient_occlusion); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(!h.app.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"open":"Graphics", "ambient_occlusion":true})); + h.call("ui.prefs", json!({"button":"apply"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(!h.app.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"button":"cancel"})); + assert!(h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.ambient_occlusion","params":{"enabled":false}})); + assert!(!h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.ambient_occlusion","params":{"enabled":"yes"}})); + assert!(!h.app.preferences.ambient_occlusion); + h.app.start("view.ambient_occlusion"); + assert!(h.app.preferences.ambient_occlusion); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), design); + assert!(h.app.session.undo.is_empty()); + } +} + +/// Manual edits are preserved and shown as Custom rather than claiming to match a preset. +pub(crate) fn graphics_preset(prefs: &Prefs) -> &'static str { + match (prefs.ambient_occlusion, prefs.display_quality.as_str(), prefs.supersampling, prefs.supersampling_adaptive) { + (false, "normal", 1.0, _) => "performance", + (true, "fine", 2.0, true) => "quality", + _ => "custom", + } +} + +#[cfg(test)] +mod graphics_preset_tests { + use super::*; + + #[test] + fn viewport_preset_popup_accepts_quality_and_performance() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.inspect", json!({})); + for handle in ["nav:view", "view:graphics_preset", "view:graphics_preset:quality"] { + let pos = crate::scenario::handle_at(handle).unwrap(); + h.call("ui.click", json!({"x":pos.x,"y":pos.y})); + } + assert!(h.app.preferences.ambient_occlusion); + for handle in ["view:graphics_preset", "view:graphics_preset:performance"] { + let pos = crate::scenario::handle_at(handle).unwrap(); + h.call("ui.click", json!({"x":pos.x,"y":pos.y})); + } + assert!(!h.app.preferences.ambient_occlusion); + } + + #[test] + fn quality_selector_enables_ao_and_supports_persistence_and_cancel() { + let mut h = crate::scenario::Harness::new(); + let camera = h.app.cam; + let design = h.app.session.doc.to_json(); + let msaa = h.app.preferences.msaa; + h.call("ui.prefs", json!({"open":"Graphics"})); + for handle in ["view:graphics_preset", "view:graphics_preset:quality"] { + let pos = crate::scenario::handle_at(handle).unwrap(); + h.call("ui.click", json!({"x":pos.x,"y":pos.y})); + } + assert!(h.app.preferences.ambient_occlusion); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.ambient_occlusion); + h.call("ui.prefs", json!({"button":"cancel"})); + assert_eq!(graphics_preset(&h.app.preferences), "performance"); + assert!(!h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}})); + assert!(h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"invalid"}})); + assert!(h.app.preferences.ambient_occlusion); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"performance"}})); + assert!(!h.app.preferences.ambient_occlusion); + assert_eq!(graphics_preset(&h.app.preferences), "performance"); + assert_eq!(h.app.preferences.display_quality, "normal"); + assert_eq!(h.app.preferences.supersampling, 1.0); + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}})); + assert_eq!(graphics_preset(&h.app.preferences), "quality"); + assert_eq!(h.app.preferences.display_quality, "fine"); + assert_eq!(h.app.preferences.supersampling, 2.0); + assert!(h.app.preferences.supersampling_adaptive); + for edit in [ + json!({"display_quality":"ultra"}), + json!({"supersampling":1.5}), + json!({"supersampling_adaptive":false}), + json!({"ambient_occlusion":false}), + ] { + h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}})); + h.call("ui.prefs", edit); + assert_eq!(graphics_preset(&h.app.preferences), "custom"); + } + assert_eq!(graphics_preset(&restored.preferences), "quality"); + h.call("ui.prefs", json!({"open":"Graphics"})); + h.call("ui.prefs", json!({"button":"defaults"})); + assert_eq!(graphics_preset(&h.app.preferences), "performance"); + h.call("ui.prefs", json!({"button":"ok"})); + assert_eq!(h.app.preferences.msaa, msaa); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), design); + assert!(h.app.session.undo.is_empty()); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/delta-LF-review.patch b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/delta-LF-review.patch new file mode 100644 index 000000000..0f6a96c2d --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/delta-LF-review.patch @@ -0,0 +1,125 @@ +--- /dev/null ++++ b/assets/locales/pending/cpu-progressive-policy-preferences.json +@@ -0,0 +1,44 @@ ++{ ++ "de": { ++ "prefs.cpu_render_advanced": "Erweitertes CPU-Rendering", ++ "prefs.render_cpu_interactive_explicit_sampling": "Erfasste progressive Abtastung in Interactive verwenden", ++ "prefs.render_cpu_interactive_explicit_sampling_help": "Verwendet das erfasste Abtastziel und den Zufallsstartwert. Aus stellt nur für Interactive 16 Abtastungen und Startwert 0 wieder her. Ohne progressive Anfrage bleibt 16/0; finale Einstellungen bleiben unverändert.", ++ "prefs.render_cpu_progressive_every_pass": "Jeden vollständigen CPU-Durchgang veröffentlichen", ++ "prefs.render_cpu_progressive_every_pass_help": "Veröffentlicht jeden vollständigen nichtfinalen Durchgang bei verfügbarem Snapshot-Speicher. Aus stellt die frühere sparsame Rückmeldung wieder her. Das Ziel bleibt gleich; die Anzeige kann Aktualisierungen zusammenfassen." ++ }, ++ "en": { ++ "prefs.cpu_render_advanced": "Advanced CPU rendering", ++ "prefs.render_cpu_interactive_explicit_sampling": "Use captured progressive sampling in Interactive", ++ "prefs.render_cpu_interactive_explicit_sampling_help": "Use the captured progressive target and seed. Off restores 16 samples and seed 0 for Interactive only. An absent progressive request still uses 16/0; final settings are unchanged.", ++ "prefs.render_cpu_progressive_every_pass": "Publish every complete CPU pass", ++ "prefs.render_cpu_progressive_every_pass_help": "Publish each complete nonfinal pass when snapshot storage is available. Off restores the earlier sparse feedback policy. The target is unchanged; the screen may combine updates." ++ }, ++ "es": { ++ "prefs.cpu_render_advanced": "Renderizado CPU avanzado", ++ "prefs.render_cpu_interactive_explicit_sampling": "Usar el muestreo progresivo capturado en Interactive", ++ "prefs.render_cpu_interactive_explicit_sampling_help": "Usa el objetivo y la semilla progresivos capturados. Desactivado restaura 16 muestras y semilla 0 solo en Interactive. Sin petición progresiva se conserva 16/0; los ajustes finales no cambian.", ++ "prefs.render_cpu_progressive_every_pass": "Publicar cada pasada CPU completa", ++ "prefs.render_cpu_progressive_every_pass_help": "Publica cada pasada completa no final cuando hay espacio para snapshots. Desactivado restaura la política anterior de actualizaciones espaciadas. El objetivo no cambia; la pantalla puede agrupar actualizaciones." ++ }, ++ "ja": { ++ "prefs.cpu_render_advanced": "CPUレンダリングの詳細設定", ++ "prefs.render_cpu_interactive_explicit_sampling": "Interactiveで取得済みのプログレッシブ設定を使用", ++ "prefs.render_cpu_interactive_explicit_sampling_help": "取得済みの目標サンプル数とシードを使用します。オフではInteractiveのみ16サンプル、シード0に戻ります。プログレッシブ指定がない場合は16/0を維持し、最終設定は変わりません。", ++ "prefs.render_cpu_progressive_every_pass": "CPUの各完了パスを公開", ++ "prefs.render_cpu_progressive_every_pass_help": "スナップショット用の空きがある場合、最終以外の各完了パスを公開します。オフでは以前の間隔を空けた更新方針に戻ります。目標は変わらず、画面更新はまとめられる場合があります。" ++ }, ++ "ko": { ++ "prefs.cpu_render_advanced": "고급 CPU 렌더링", ++ "prefs.render_cpu_interactive_explicit_sampling": "Interactive에서 캡처한 점진적 샘플링 사용", ++ "prefs.render_cpu_interactive_explicit_sampling_help": "캡처한 샘플 목표와 시드를 사용합니다. 끄면 Interactive만16샘플과 시드0으로 돌아갑니다. 점진적 요청이 없으면16/0을 유지하며 최종 설정은 바뀌지 않습니다.", ++ "prefs.render_cpu_progressive_every_pass": "완료된 CPU 패스마다 게시", ++ "prefs.render_cpu_progressive_every_pass_help": "스냅샷 공간이 있으면 마지막을 제외한 각 완료 패스를 게시합니다. 끄면 이전의 간헐적 피드백 정책으로 돌아갑니다. 목표는 그대로이며 화면 업데이트가 합쳐질 수 있습니다." ++ }, ++ "zh": { ++ "prefs.cpu_render_advanced": "高级CPU渲染", ++ "prefs.render_cpu_interactive_explicit_sampling": "在Interactive中使用已捕获的渐进采样设置", ++ "prefs.render_cpu_interactive_explicit_sampling_help": "使用已捕获的采样目标和种子。关闭后,仅Interactive恢复为16个样本和种子0。未指定渐进请求时仍使用16/0;最终设置不变。", ++ "prefs.render_cpu_progressive_every_pass": "发布每个完整的CPU遍次", ++ "prefs.render_cpu_progressive_every_pass_help": "快照空间可用时,发布最终遍次之前的每个完整遍次。关闭后恢复之前间隔更新的策略。目标不变;屏幕可能合并更新。" ++ } ++} +--- a/crates/ui-egui/src/prefs.rs ++++ b/crates/ui-egui/src/prefs.rs +@@ -942,6 +942,10 @@ + render_previous_geometry_budget: bool = false, PAGE_GRAPHICS => check_id("prefs.render_previous_geometry_budget"); + /// Open Result once after a successful GUI Start; false preserves the selected view. + render_open_result_on_start: bool = true, PAGE_GRAPHICS => check_id("prefs.render_open_result_on_start"); ++ /// CPU snapshot boundaries; false restores powers-of-two feedback without changing the sample target. ++ render_cpu_progressive_every_pass: bool = true, PAGE_GRAPHICS => check_id("prefs.render_cpu_progressive_every_pass"); ++ /// Interactive sampling policy; false restores its old16SPP/seed0 envelope. ++ render_cpu_interactive_explicit_sampling: bool = true, PAGE_GRAPHICS => check_id("prefs.render_cpu_interactive_explicit_sampling"); + /// How finely the viewport tessellates curved faces and edges: `coarse`, `normal`, `fine` or + /// `ultra` (#1287). Only the display plan the viewport draws; never the design or exports. + display_quality: String = "normal".into(), PAGE_GRAPHICS; +@@ -2278,10 +2282,25 @@ + PAGE_INTERFACE => interface::interface(app, ui, t), + PAGE_DESIGN => design::show(app, ui), + PAGE_NAVIGATION => navigation::show(app, ui, t), +- PAGE_GRAPHICS => graphics::show(app, ui), ++ PAGE_GRAPHICS => { ++ graphics::show(app, ui); ++ cpu_progressive_advanced_preferences(app, ui); ++ } + PAGE_SKETCH => sketch::show(app, ui), + _ => {} + } ++} ++ ++fn cpu_progressive_advanced_preferences(app: &mut SolveApp, ui: &mut egui::Ui) { ++ let title = app.tr("prefs.cpu_render_advanced").to_string(); ++ ui_kit::section(ui, "prefs_cpu_render_advanced", &title, false, |ui| { ++ let response = setting::render_cpu_progressive_every_pass(app, ui) ++ .on_hover_text(app.tr("prefs.render_cpu_progressive_every_pass_help")); ++ crate::scenario::publish_target("prefs:render-cpu-progressive-every-pass", response.rect); ++ let response = setting::render_cpu_interactive_explicit_sampling(app, ui) ++ .on_hover_text(app.tr("prefs.render_cpu_interactive_explicit_sampling_help")); ++ crate::scenario::publish_target("prefs:render-cpu-interactive-explicit-sampling", response.rect); ++ }); + } + + fn page_index(name: &str) -> Option { +@@ -3334,6 +3353,37 @@ + #[cfg(test)] + mod tests { + #[test] ++ fn cpu_progressive_policy_preferences_default_roundtrip_validate_and_reset_independently() { ++ let defaults = Prefs::default(); ++ assert!(defaults.render_cpu_progressive_every_pass && defaults.render_cpu_interactive_explicit_sampling); ++ let omitted: Prefs = serde_json::from_value(json!({})).unwrap(); ++ assert!(omitted.render_cpu_progressive_every_pass && omitted.render_cpu_interactive_explicit_sampling); ++ let mut app = SolveApp::new(Default::default(), Default::default()); ++ let document = app.session.doc.clone(); ++ let history = (app.session.revision, app.session.undo.len(), app.session.is_dirty()); ++ for key in ["render_cpu_progressive_every_pass", "render_cpu_interactive_explicit_sampling"] { ++ let reply = super::set(&mut app, &json!({key:false})).unwrap(); ++ assert_eq!(reply[key], false); ++ for invalid in [json!("false"), json!(0), json!(null), json!([])] { ++ assert!(super::set(&mut app, &json!({key:invalid})).is_err()); ++ assert_eq!(serde_json::to_value(&app.preferences).unwrap()[key], false); ++ } ++ } ++ let mut restored = SolveApp::new(Default::default(), Default::default()); ++ restored.load_prefs(&app.prefs()); ++ assert!(!restored.preferences.render_cpu_progressive_every_pass && !restored.preferences.render_cpu_interactive_explicit_sampling); ++ super::defaults(&mut restored, super::PAGE_GENERAL); ++ assert!(!restored.preferences.render_cpu_progressive_every_pass && !restored.preferences.render_cpu_interactive_explicit_sampling); ++ let reply = super::set(&mut restored, &json!({"render_cpu_progressive_every_pass":true})).unwrap(); ++ assert_eq!(reply["render_cpu_progressive_every_pass"], true); ++ assert_eq!(reply["render_cpu_interactive_explicit_sampling"], false); ++ super::defaults(&mut restored, super::PAGE_GRAPHICS); ++ assert!(restored.preferences.render_cpu_progressive_every_pass && restored.preferences.render_cpu_interactive_explicit_sampling); ++ assert!(std::sync::Arc::ptr_eq(&document, &app.session.doc)); ++ assert_eq!(history, (app.session.revision, app.session.undo.len(), app.session.is_dirty())); ++ } ++ ++ #[test] + fn render_open_result_on_start_defaults_persists_validates_and_resets() { + assert!(Prefs::default().render_open_result_on_start); + assert!(serde_json::from_value::(json!({})).unwrap().render_open_result_on_start); diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/source-bindings.json b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/source-bindings.json new file mode 100644 index 000000000..ad6b03225 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/prefs/source-bindings.json @@ -0,0 +1,29 @@ +{ + "status": "SOURCE_ONLY_NOT_ADOPTED_UNCOMPILED_UNRUN", + "subpackage": "prefs", + "base_source_manifest_sha256": "d38a8d946b6653864ad8918d4da662725bd24ca01b2e5aa2d3b38b47b1a7e163", + "base_rule": "Exact per-file RAW preimages only. Not current main, not a combined candidate. LF patch is review aid; RAW candidate bytes are authoritative.", + "files": [ + { + "path": "assets/locales/pending/cpu-progressive-policy-preferences.json", + "before_sha256": null, + "before_bytes": null, + "after_sha256": "18fc39ddb923c03eb640f02f860c8ae10d9debf8843b1b9eadb9b0e0ce397f20", + "after_bytes": 4818 + }, + { + "path": "crates/ui-egui/src/prefs.rs", + "before_sha256": "b90ea63d6238bf41cb467a41efcd2b3888196e3be60f2453c635078d0933c97d", + "before_bytes": 378635, + "after_sha256": "b24b15f754e2ab01f5b3dc084db3fe214474669c936da244a189e708c8cb6b11", + "after_bytes": 382245 + } + ], + "full_CI_native_or_readiness": false, + "candidate_whole_file_overlay_safe": true, + "locale_successor_lineage": { + "intermediate_before_sha256": "6d9e78b16fc3d8e015467c6512fb6401fd01b64ae871e8d643bdd61669fb154a", + "successor_after_sha256": "18fc39ddb923c03eb640f02f860c8ae10d9debf8843b1b9eadb9b0e0ce397f20", + "new_original_base_file": true + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/README.md b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/README.md new file mode 100644 index 000000000..a9f404b02 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/README.md @@ -0,0 +1,20 @@ +# Capture and Interactive compatibility WIP + +Five exact RAW candidates, **NOT ADOPTED, UNCOMPILED, UNRUN**. Requires the core +canonical field and the prefs package. Five new tests are written, not run. +The transient command Value carries false only for effective progressive CPU +requests, including Interactive derived from a Fixed final editor. Single final, +Raster and GPU commands omit it. Legacy 16/seed0 sampling changes only an +Interactive request copy, after original numerical validation; it does not +weaken final admission or change saved/editor intent. + +The Snapshot test uses frozen real command input. The UI invalidation test holds +a real already-completed callback; it does not establish in-flight cancellation +or physical presentation of every pass. Native CPU-supported branches and full +validation remain pending. Four workspace-test constructors, one render test +constructor and one thumbnail constructor receive neutral true fields only. + +**Overlap:** this candidate render_workspace_tests.rs and fontfix both use RAW +before 28ddafe4. This whole file does not contain the separate font correction. +Compose exact deltas with review; copying either full candidate over the other +would lose work. No combined candidate is supplied here. diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/render/src/job/interactive.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/render/src/job/interactive.rs new file mode 100644 index 000000000..21672ae04 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/render/src/job/interactive.rs @@ -0,0 +1,372 @@ +//! 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 { + 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, + changed_at: Duration, + enabled: bool, + paused: bool, + final_active: bool, + ticket: Option, + active: Option, + error: Option, +} + +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> { + 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 { + // 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 { + 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 { + cpu_progressive_every_pass: true, + 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"); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace.rs new file mode 100644 index 000000000..26a1beb86 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace.rs @@ -0,0 +1,2516 @@ +//! Integrated product preview. Shares the installed device/pipelines, not Design's scene policy. + +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use egui::{Color32, Sense}; +use serde_json::json; +use solidcraft_engine::doc::render_settings::RenderSetup; +#[cfg(test)] +use solidcraft_engine::render::job::LightingPreset; +use solidcraft_engine::render::job::{ImageHost, Integrator, JobId, PartialPreviewInfo, PreviewInfo, ProtectedPreviewReport, RaytraceOptions}; +use solidcraft_engine::render::{ + Availability, Camera, ExecutorDescriptor, ExecutorId, ProductScene, RenderLimits, RenderMode, RenderOperation, RenderProfile, RenderRequest, + ScratchLayout, +}; + +use crate::gpu::{Frame, GpuScene, SceneSlot, ViewportCallback}; +use crate::{SolveApp, theme::Tokens}; + +// Vertex payload only, not an OS/GPU peak-memory promise. Native viewport +// uploads are already chunked by the installed device's buffer limit. +const MAX_GEOMETRY_BYTES: usize = + if cfg!(all(not(target_arch = "wasm32"), target_pointer_width = "64")) { 512 * 1024 * 1024 } else { 128 * 1024 * 1024 }; + +#[path = "render_workspace_ribbon.rs"] +mod ribbon; + +#[path = "render_workspace_cpu.rs"] +mod cpu; + +#[path = "render_workspace_hdr.rs"] +mod hdr; + +#[path = "render_workspace_effects.rs"] +mod effects; +#[path = "render_workspace_environment.rs"] +mod environment; +#[path = "render_workspace_inspector.rs"] +mod inspector; + +#[path = "render_workspace_interactive.rs"] +pub(crate) mod interactive; + +#[path = "render_workspace_library.rs"] +mod library; + +#[path = "render_ui/assign.rs"] +pub(crate) mod assign; +#[path = "render_workspace_light.rs"] +pub(crate) mod light; + +#[path = "render_workspace_materials.rs"] +mod materials; + +#[path = "render_workspace_setups.rs"] +mod setups; + +#[path = "render_workspace_shot.rs"] +pub(crate) mod shot; + +#[path = "render_workspace_shots.rs"] +pub(crate) mod shots; + +#[path = "render_ui/scene.rs"] +pub(crate) mod scene; + +#[path = "render_workspace_studio.rs"] +mod studio; +#[path = "render_workspace_transport.rs"] +mod transport; + +#[path = "render_workspace_thumbnails.rs"] +mod thumbnails; +#[path = "render_ui/wear.rs"] +mod wear; + +/// The browser's preview budget: WebGPU and WebGL share the tab's memory, so it stays small. +const WEB_GEOMETRY_BYTES: u64 = 128 * 1024 * 1024; +/// Desktop: at most this many of the device's largest buffers of geometry... +const DESKTOP_GEOMETRY_BUFFERS: u64 = 8; +/// ...and never more than this, whatever the device allows. +const DESKTOP_GEOMETRY_CEILING: u64 = 2 * 1024 * 1024 * 1024; + +/// The product preview's geometry budget for a device whose largest buffer is `max_buffer_size` +/// bytes (`wgpu::Device::limits`, what the device was created with). Uploads are split into +/// buffers of at most that size, so the budget bounds memory, not a single buffer: 2 GiB on a +/// device with the standard 256 MiB buffers. An allocation the device still refuses is caught +/// by the upload's error scope and reported, not a crash. +pub(crate) fn geometry_budget(max_buffer_size: u64, web: bool) -> u64 { + if web { WEB_GEOMETRY_BYTES } else { max_buffer_size.saturating_mul(DESKTOP_GEOMETRY_BUFFERS).min(DESKTOP_GEOMETRY_CEILING) } +} + +/// Apply the saved compatibility preference to the device-derived budget. +fn preferred_geometry_budget(device_budget: u64, previous: bool) -> u64 { + if previous { MAX_GEOMETRY_BYTES as u64 } else { device_budget } +} + +fn admit_geometry(bytes: u64, budget: u64) -> Result<(), String> { + if bytes > budget { + return Err(format!( + "Render preview needs {:.1} MiB of geometry; the limit is {:.1} MiB. Hide bodies in Design, then return to Render and try again.", + bytes as f64 / 1048576.0, + budget as f64 / 1048576.0 + )); + } + Ok(()) +} + +/// The message when the device refused the preview's geometry. +fn upload_refusal(bytes: u64, error: &str) -> String { + format!( + "The graphics device could not hold the Render preview's {:.1} MiB of geometry ({error}). Hide bodies in Design, then return to Render and try again.", + bytes as f64 / 1048576.0 + ) +} + +#[cfg(test)] +#[path = "render_workspace_tests.rs"] +mod tests; + +type PathFactory = Box Result + Send>; + +pub struct State { + thumbnails: thumbnails::Cache, + pending_setup: Option, + pub host: Option, + pub path_host: PathHost, + /// How long the last path tracer setup took, in seconds, per viewport adapter + /// ([`adapter_key`]); kept in the preferences to estimate the next one. + pub setup_seconds: std::collections::BTreeMap, + /// The viewport adapter the current setup runs on. + pub setup_key: Option, + pub geometry_budget: u64, + /// A GPU error the preview's last geometry upload caught. + pub upload_error: crate::gpu::UploadError, + pub image_host: Option, + pub view: ViewState, + interactive: interactive::State, + revision: u64, + design_camera: Option<(Camera, bool)>, + slot: SceneSlot, + key: Option, + scene_signature: Option<(u64, usize, u64, u64)>, + scene: Option, + scene_error: Option, + preview_upload_bytes: Option, + image: Option<(solidcraft_engine::render::job::JobId, Result)>, + image_info: Option, + preview_image: Option, + final_partial: Option, + final_partial_request: Option<(JobId, Duration)>, + final_feedback_clock: Duration, + final_feedback_report: Option<(JobId, ProtectedPreviewReport)>, + clipboard_image: Option, + clipboard_text: Option, +} + +/// Provisional pixels are never an export source and never replace the retained final image. +struct PreviewImage { + info: PreviewInfo, + image: Result, +} + +struct FinalPartialImage { + info: PartialPreviewInfo, + sampling: interactive::PartialSampling, + image: Result, +} + +struct DisplayImage<'a> { + info: &'a solidcraft_engine::render::job::FrameInfo, + image: &'a Result, + preview: Option<&'a PreviewInfo>, + partial: Option<(&'a PartialPreviewInfo, interactive::PartialSampling)>, + logical_size: [u32; 2], +} + +impl DisplayImage<'_> { + fn provisional(&self) -> bool { + self.preview.is_some() || self.partial.is_some() + } +} + +/// Application-wide setup, retained across document changes. The worker owns a +/// cloned adapter and initializes the job device; the UI receives the finished host. +#[derive(Default)] +pub enum PathHost { + #[default] + NotStarted, + /// The worker's answer, and when it started: shader compilation can take minutes. + Preparing(std::sync::mpsc::Receiver>, std::time::Instant), + Ready(ImageHost), + Failed(String), +} + +impl PathHost { + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn start(&mut self, create: impl FnOnce() -> Result + Send + 'static) { + if !matches!(self, Self::NotStarted) { + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + // Dropping the handle detaches: neither startup nor shutdown joins a driver + // that may spend minutes compiling or warming up its pipelines. + *self = match std::thread::Builder::new().name("gpu-path-setup".into()).spawn(move || { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(create)) + .unwrap_or_else(|_| Err(crate::i18n::tr("render.error_setup_panicked").into())); + let _ = tx.send(result); + }) { + Ok(_) => Self::Preparing(rx, std::time::Instant::now()), + Err(e) => Self::failed(crate::i18n::format("render.error_setup_worker", &[("error", &e.to_string())])), + }; + } + + fn failed(message: String) -> Self { + log::warn!("progressive render unavailable: {message}"); + Self::Failed(message) + } + + /// Take the worker's answer if it has come; returns how long a successful setup took. + fn poll(&mut self) -> Option { + let Self::Preparing(rx, started) = self else { return None }; + let took = started.elapsed(); + *self = match rx.try_recv() { + Ok(Ok(host)) => Self::Ready(host), + Ok(Err(error)) => Self::failed(error), + Err(std::sync::mpsc::TryRecvError::Empty) => return None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Self::failed(crate::i18n::tr("render.error_setup_stopped").into()), + }; + matches!(self, Self::Ready(_)).then_some(took) + } +} + +/// The samples slider's top end: 2^12 = 4096 samples per pixel. +#[cfg(test)] +const MAX_SAMPLES_EXPONENT: u32 = 12; + +/// Setup times kept per adapter, at most. +const MAX_SETUP_TIMES: usize = 16; + +/// The key [`State::setup_seconds`] files an adapter's setup time under: a driver update +/// usually empties the driver's shader cache, so the driver is part of it. +pub fn adapter_key(info: &egui_wgpu::wgpu::AdapterInfo) -> String { + format!("{} | {:?} | {} {}", info.name.trim(), info.backend, info.driver.trim(), info.driver_info.trim()) +} + +/// Remember how long the setup on `key` took, for the next start's estimate. +fn record_setup(state: &mut State, took: std::time::Duration) { + let Some(key) = state.setup_key.clone() else { return }; + if state.setup_seconds.len() >= MAX_SETUP_TIMES && !state.setup_seconds.contains_key(&key) { + return; + } + state.setup_seconds.insert(key, took.as_secs_f64()); +} + +/// Setup times from the preferences: finite, non-negative and at most a day each. +pub fn load_setup_seconds(value: &serde_json::Value) -> std::collections::BTreeMap { + value + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.clone(), v.as_f64().filter(|s| s.is_finite() && (0.0..=86_400.0).contains(s))?))) + .take(MAX_SETUP_TIMES) + .collect() +} + +/// Minutes and seconds, as `1:05`. +fn mmss(d: std::time::Duration) -> String { + let s = d.as_secs(); + format!("{}:{:02}", s / 60, s % 60) +} + +/// The path tracer's setup as it goes: a progress bar estimated from the last setup on this +/// adapter, else a spinner with the time so far. Drivers report no progress of their own. +fn setup_progress(ui: &mut egui::Ui, app: &SolveApp, started: std::time::Instant) { + let elapsed = started.elapsed(); + let expected = app.render_workspace.setup_key.as_ref().and_then(|k| app.render_workspace.setup_seconds.get(k)).copied(); + ui.label(app.tr("render.gpu_path_preparing")); + match expected.map(|s| std::time::Duration::from_secs_f64(s.max(1.0))) { + Some(expected) if elapsed < expected.mul_f64(1.5) => { + let fraction = (elapsed.as_secs_f32() / expected.as_secs_f32()).min(0.99); + crate::ui_kit::progress(ui, "gpu_path_setup", fraction); + ui.label(format!("{} / ~{}", mmss(elapsed), mmss(expected))); + // The bar moves with time, so keep drawing while it is shown. + ui.ctx().request_repaint_after(std::time::Duration::from_millis(250)); + } + _ => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(mmss(elapsed)); + }); + if expected.is_none() { + ui.small(app.tr("render.gpu_path_first_setup")); + } + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Stage { + #[default] + Look, + Light, + Frame, + Output, +} +impl Stage { + pub(crate) const ALL: [Self; 4] = [Self::Look, Self::Light, Self::Frame, Self::Output]; + pub(crate) fn key(self) -> &'static str { + match self { + Self::Look => "look", + Self::Light => "light", + Self::Frame => "frame", + Self::Output => "output", + } + } + pub(crate) fn label(self) -> &'static str { + match self { + Self::Look => "render.stage_look", + Self::Light => "render.stage_light", + Self::Frame => "render.stage_frame", + Self::Output => "render.stage_output", + } + } + fn page(self) -> inspector::Page { + match self { + Self::Look => inspector::Page::Appearance, + Self::Light => inspector::Page::Lighting, + Self::Frame => inspector::Page::Camera, + Self::Output => inspector::Page::Output, + } + } +} + +/// Browser focus is transient per-document view state, never part of a saved design. +#[derive(Clone, Debug, Default, PartialEq)] +pub enum RenderSelection { + #[default] + Nothing, + Object(Vec), + Environment, + Wear, + Lighting, + /// Method/type/index identity until named light commands provide persistent IDs. + Light(String), + Shot(String), + Output, + Sampling, + Effects, + Check, +} + +/// Selection-driven homes introduced by E1/E7; remaining editors retain their adapters. +pub(crate) fn selection_editor(app: &mut SolveApp, selection: &RenderSelection) { + app.render_workspace.view.inspector.page = match selection { + RenderSelection::Nothing => inspector::Page::Scene, + RenderSelection::Shot(_) => inspector::Page::Camera, + RenderSelection::Output => inspector::Page::Output, + _ => return, + }; +} + +pub(crate) fn select_lighting(app: &mut SolveApp) { + app.render_workspace.view.inspector.page = inspector::Page::Lighting; +} + +/// Small per-document editor state; GPU uploads and host capabilities stay outside tabs. +#[derive(Clone, Debug)] +pub struct ViewState { + pub(crate) assign: assign::State, + pub(crate) frame: shot::Frame, + lights: light::View, + job_shot: Option, + save_shot_name: Option, + pub name: String, + pub selection: RenderSelection, + pub(crate) stage: Stage, + pub(crate) by_look: bool, + pub(crate) search_objects: bool, + pub(crate) object_query: String, + draft: RenderSetup, + dirty: bool, + clean_setup: Option, + job: Option, + completed: Option, + transparent: bool, + method: ImageMethod, + raytrace: RaytraceOptions, + samples: u32, + max_depth: u32, + seed: u32, + studio: studio::View, + materials: materials::View, + library: library::View, + inspector: inspector::View, + environment_ring: environment::RingView, + + cpu: cpu::View, + overwrite: bool, + result: bool, + result_camera: Camera, + result_scale: ResultScale, + result_job: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum ResultScale { + #[default] + Fit, + Actual, + Free, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum ImageMethod { + #[default] + Raster, + CpuRaytrace, + GpuRaytrace, +} + +impl ImageMethod { + fn label(self) -> &'static str { + match self { + Self::Raster => "render.method_raster", + Self::CpuRaytrace => "render.method_cpu", + Self::GpuRaytrace => "render.method_gpu", + } + } +} + +impl Default for ViewState { + fn default() -> Self { + Self { + assign: assign::State::default(), + lights: Default::default(), + job_shot: None, + frame: Default::default(), + save_shot_name: None, + name: "Studio".into(), + selection: RenderSelection::Nothing, + stage: Stage::Look, + by_look: false, + search_objects: false, + object_query: String::new(), + draft: RenderSetup::default(), + dirty: false, + clean_setup: None, + job: None, + completed: None, + transparent: false, + method: ImageMethod::Raster, + raytrace: RaytraceOptions::default(), + samples: 64, + max_depth: 8, + seed: 0, + studio: studio::View::default(), + materials: materials::View::default(), + library: library::View::default(), + inspector: inspector::View::default(), + environment_ring: environment::RingView::default(), + + cpu: cpu::View::default(), + overwrite: false, + result: false, + result_camera: Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..Default::default() }, + result_scale: ResultScale::Fit, + result_job: None, + } + } +} + +impl Default for State { + fn default() -> Self { + Self { + thumbnails: Default::default(), + host: None, + path_host: PathHost::default(), + pending_setup: None, + setup_seconds: Default::default(), + setup_key: None, + geometry_budget: WEB_GEOMETRY_BYTES, + upload_error: Arc::new(Mutex::new(None)), + image_host: None, + view: Default::default(), + interactive: Default::default(), + revision: u64::MAX, + design_camera: None, + slot: Arc::new(Mutex::new(None)), + key: None, + scene_signature: None, + scene: None, + scene_error: None, + preview_upload_bytes: None, + image: None, + image_info: None, + preview_image: None, + final_partial: None, + final_partial_request: None, + final_feedback_clock: Duration::ZERO, + final_feedback_report: None, + clipboard_image: None, + clipboard_text: None, + } + } +} + +impl State { + /// Retain the selected viewport adapter, but do not open another device or + /// compile shaders until GPU path tracing is selected in Render. Raster and + /// CPU image methods retain this factory without starting it. A later viewport + /// installation (for example safe-mode fallback) replaces only an unstarted factory. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn defer_path_host(&mut self, key: String, create: impl FnOnce() -> Result + Send + 'static) { + if matches!(self.path_host, PathHost::NotStarted) { + self.setup_key = Some(key); + self.pending_setup = Some(Box::new(create)); + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn start_deferred_path_host(&mut self) { + if self.view.method == ImageMethod::GpuRaytrace + && matches!(self.path_host, PathHost::NotStarted) + && let Some(create) = self.pending_setup.take() + { + self.path_host.start(create); + } + } +} + +pub fn active(app: &SolveApp) -> bool { + crate::workspace::render_tab(&app.ui.tab) +} + +pub(crate) fn result_active(app: &SolveApp) -> bool { + active(app) && app.render_workspace.view.result +} + +pub(crate) fn fit_result(app: &mut SolveApp) { + app.render_workspace.view.result_scale = ResultScale::Fit; +} + +/// Read-only identities for automation and diagnostics. Does not prepare a +/// request, open a device, evaluate geometry, change the selected result or pump +/// a job. Clients must use render.status for the exact identity returned here. +pub(crate) fn inspect_state(app: &SolveApp) -> serde_json::Value { + let view = &app.render_workspace.view; + let method = match view.method { + ImageMethod::Raster => "raster", + ImageMethod::CpuRaytrace => "cpu_raytrace", + ImageMethod::GpuRaytrace => "gpu_path", + }; + json!({ + "active": active(app), "stage": view.stage.key(), "setup": view.name, "draft_dirty": view.dirty, + "method": method, "job": view.job, "completed": view.completed, + "interactive": interactive::inspect(app), + "final_partial": app.render_workspace.final_partial.as_ref().map(|partial| &partial.info), + "final_feedback_report": app.render_workspace.final_feedback_report.map(|(job, report)| json!({"job":job,"report":report})), + "showing_result": view.result, "export_format": if view.studio.export_exr {"exr"} else {"png"}, + }) +} + +pub fn host_executor(max_dimension: u32, depth: bool, samples: u32) -> Result { + if !matches!(samples, 1 | 2 | 4 | 8 | 16) { + return Err(crate::i18n::tr("render.error_gpu_samples").into()); + } + Ok(ExecutorDescriptor { + id: ExecutorId::new("gpu-viewport").map_err(|e| e.to_string())?, + availability: if depth && max_dimension > 0 { + Availability::Available + } else { + Availability::Unavailable { reason: crate::i18n::tr("render.error_preview_device").into() } + }, + profiles: vec![RenderProfile { + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + formats: Vec::new(), + features: vec![solidcraft_engine::render::RenderFeature::Pbr], + }], + limits: RenderLimits { max_dimension: u64::from(max_dimension.clamp(1, 4096)), ..Default::default() }, + scratch: ScratchLayout { + sample_scale: 1, + sample_bytes_per_pixel: 8 * u64::from(samples), + output_bytes_per_pixel: 8, + encoding_bytes_per_pixel: 0, + }, + }) +} + +pub fn sync_backend(app: &mut SolveApp) { + #[cfg(not(target_arch = "wasm32"))] + if active(app) { + app.render_workspace.start_deferred_path_host(); + } + if let Some(took) = app.render_workspace.path_host.poll() { + record_setup(&mut app.render_workspace, took); + } + if let PathHost::Ready(host) = &app.render_workspace.path_host + && let Err(e) = app.session.register_render_job_host(host.clone()) + { + app.render_workspace.path_host = PathHost::failed(e.to_string()); + app.set_status(e.to_string(), true); + } + + if app.session.render_job_host().is_none() + && let Some(host) = &app.render_workspace.image_host + && let Err(e) = app.session.set_render_job_host(Some(host.clone())) + { + app.set_status(e.to_string(), true); + } + if app.session.render_viewport() == app.render_workspace.host.as_ref() { + return; + } + if let Err(e) = app.session.set_render_viewport(app.render_workspace.host.clone()) { + app.set_status(e.to_string(), true); + } +} + +/// Cooperative work belongs to the frame loop, never to a status/control request. Keep +/// scheduling frames even after leaving Render so a browser job can finish in Design. +pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { + interactive::tick(app, ctx); + if let Some(text) = app.render_workspace.clipboard_text.take() { + ctx.copy_text(text); + } + if let Some(image) = app.render_workspace.clipboard_image.take() { + ctx.copy_image(image); + } + if matches!(app.render_workspace.path_host, PathHost::Preparing(..)) { + // Poll even in Design or an idle window, without continuously redrawing. + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + if let Some(host) = &app.render_workspace.image_host { + match host.pump(1024) { + Ok(true) => ctx.request_repaint(), + Ok(false) => {} + Err(e) => app.set_status(e.to_string(), true), + } + } + if app.render_workspace.view.job.is_some() { + cache_render_images(app, ctx); + } +} + +pub fn reset_document(app: &mut SolveApp) { + crate::render_ui::reset_shell(app); + app.ui.ribbon_context = None; + let host = app.render_workspace.host.clone(); + let image_host = app.render_workspace.image_host.clone(); + let geometry_budget = app.render_workspace.geometry_budget; + let path_host = std::mem::take(&mut app.render_workspace.path_host); + let setup_seconds = std::mem::take(&mut app.render_workspace.setup_seconds); + let setup_key = app.render_workspace.setup_key.take(); + let pending_setup = app.render_workspace.pending_setup.take(); + let mut interactive = std::mem::take(&mut app.render_workspace.interactive); + interactive.reset_document(); + app.render_workspace = + State { host, image_host, path_host, setup_seconds, setup_key, pending_setup, geometry_budget, interactive, ..Default::default() }; + if active(app) { + app.ui.tab = "MODEL".into(); + } + sync_backend(app); +} + +pub(crate) fn invalidate_images(app: &mut SolveApp) { + app.render_workspace.image = None; + app.render_workspace.image_info = None; + app.render_workspace.preview_image = None; + app.render_workspace.final_partial = None; +} + +pub fn invalidate_scene(app: &mut SolveApp) { + app.render_workspace.thumbnails = Default::default(); + app.render_workspace.revision = u64::MAX; + app.render_workspace.scene_signature = None; + app.render_workspace.scene = None; + app.render_workspace.scene_error = None; + app.render_workspace.preview_upload_bytes = None; + app.render_workspace.key = None; + if let Ok(mut slot) = app.render_workspace.slot.lock() { + *slot = None; + } +} + +pub fn enter(app: &mut SolveApp, render: bool) -> Result<(), String> { + if render { + if app.session.active_sketch.is_some() || app.tool.is_some() || app.dialog.is_some() || app.file_load.busy() { + return Err(crate::i18n::tr("render.error_finish_operation").into()); + } + app.run("render.scene", json!({}))?; + if !active(app) { + app.render_workspace.design_camera = Some((app.cam, app.ui.perspective)); + app.ui.tab = "RENDER".into(); + select_stage(app, app.render_workspace.view.stage.key()); + if app.render_workspace.view.selection == RenderSelection::Nothing { + selection_editor(app, &RenderSelection::Nothing); + } + let scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|e| e.to_string())?; + if !scene.bounds.is_empty() { + app.fit_bounds(scene.bounds); + } + } + setups::refresh_dirty(app); + if app.render_workspace.revision != app.session.revision && !app.render_workspace.view.dirty { + setups::load(app); + } + #[cfg(not(target_arch = "wasm32"))] + app.render_workspace.start_deferred_path_host(); + } else { + app.render_workspace.interactive.reset_document(); + assign::stop(app); + if let Some((camera, perspective)) = app.render_workspace.design_camera.take() { + app.cam = camera; + app.ui.up_axis = camera.up; + app.ui.perspective = perspective; + } + app.ui.tab = "MODEL".into(); + crate::render_ui::reset_shell(app); + } + app.viewport.hover = None; + app.cam_anim = None; + if !render { + app.pending_fit = None; + } + Ok(()) +} + +/// Stage navigation is transient per-document state. It never applies a resource or starts a job. +pub(crate) fn select_stage(app: &mut SolveApp, key: &str) { + let stage = match key { + "look" => Stage::Look, + "light" => Stage::Light, + "frame" => Stage::Frame, + "output" => Stage::Output, + _ => return, + }; + app.render_workspace.view.stage = stage; + app.render_workspace.view.inspector.hidden = false; + app.render_workspace.view.inspector.page = stage.page(); + let sections: &[&str] = match stage { + Stage::Look => &["objects"], + Stage::Light => &["lights", "environment"], + Stage::Frame => &["shots"], + Stage::Output => &[], + }; + for section in sections { + app.tree.collapsed.remove(&format!("render:tree:{section}")); + } + if stage == Stage::Look { + app.tree.collapsed.remove("c0"); + app.tree.collapsed.remove("c0/bodies"); + } +} + +pub(crate) fn switch_shot(app: &mut SolveApp, name: String) { + inspector::switch_shot(app, name); +} +pub(crate) fn stage_projection(app: &mut SolveApp, perspective: bool) -> Result<(), String> { + let mut camera = app.cam; + camera.fov = if perspective { 0.6 } else { 0.0 }; + inspector::apply_camera_draft(app, camera) +} + +pub(crate) fn output_summary(app: &SolveApp) -> (String, &'static str) { + let view = &app.render_workspace.view; + (format!("{} × {}", view.draft.width, view.draft.height), if view.studio.export_exr { "EXR" } else { "PNG" }) +} + +pub(crate) fn output_child_summary(app: &SolveApp, kind: &str) -> String { + let view = &app.render_workspace.view; + match kind { + "sampling" => format!( + "{} · {} spp", + app.tr("render.quality_custom"), + if view.method == ImageMethod::GpuRaytrace { + view.samples + } else { + view.raytrace.progressive.map_or(u32::from(view.raytrace.primary_samples), |p| p.samples_per_pixel) + } + ), + "effects" => crate::i18n::format( + "render.children.look_summary", + &[ + ("tone", if view.studio.tone_map == solidcraft_engine::render::job::ToneMap::AcesFitted { "ACES" } else { "Reinhard" }), + ("count", &view.studio.finishing.looks.len().to_string()), + ], + ), + "check" => inspector::check_summary(app), + _ => String::new(), + } +} + +pub(crate) fn job_busy(app: &SolveApp) -> bool { + ribbon::busy(app) +} +pub(crate) fn output_stage_tools(app: &mut SolveApp, ui: &mut egui::Ui) { + inspector::stage_tools(app, ui); +} + +pub(crate) fn job_ready(app: &SolveApp, id: &str) -> Result<(), String> { + ribbon::action_ready(app, id) +} + +pub(crate) fn set_inspector_visible(app: &mut SolveApp, visible: bool) { + app.render_workspace.view.inspector.hidden = !visible; +} + +pub fn panel(app: &mut SolveApp, ui: &mut egui::Ui) { + if crate::render_ui::focused(app) { + return; + } + inspector::panel(app, ui); +} + +/// Interactive stage-panel review. Direct engine JSON calls remain dialog-free. +/// S5 supplies its selected specification id without owning another consent form. +pub(crate) fn review_resource(app: &mut SolveApp, command: &str, id: &str) -> Result<(), String> { + match command { + "render.quality.prepare" => library::review::quality(app, id), + _ => Err("this command has no stage-panel review adapter".into()), + } +} + +pub(crate) fn apply_browser_controls(app: &mut SolveApp, value: &serde_json::Value) { + let view = &mut app.render_workspace.view; + if let Some(by_look) = value.get("by_look").and_then(serde_json::Value::as_bool) { + view.by_look = by_look; + } + if let Some(search) = value.get("search").and_then(serde_json::Value::as_bool) { + view.search_objects = search; + } + if let Some(query) = value.get("query").and_then(serde_json::Value::as_str) { + view.object_query = query.into(); + } +} + +/// Local Browser-card content, never a new workspace or an alternative model tree. +pub(crate) fn browser_mode(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + if !active(app) { + return false; + } + if app.render_workspace.view.search_objects { + let mut query = app.render_workspace.view.object_query.clone(); + crate::ui_kit::scope(ui, |ui| { + if crate::ui_kit::search_field(ui, ui.id().with("render:tree:query"), &mut query, crate::i18n::tr("render.tree_search")).changed() { + let _ = app.run("view.render_browser", json!({"query":query})); + } + }); + } + false +} + +/// Per-stage companion sharing the Browser's dock policy. +pub(crate) fn appearances_card(app: &mut SolveApp, ui: &mut egui::Ui, bounds: egui::Rect) { + library::card(app, ui, bounds); +} + +fn image_host(app: &SolveApp, method: ImageMethod) -> Result<&ImageHost, String> { + if method == ImageMethod::GpuRaytrace { + let host = match &app.render_workspace.path_host { + PathHost::Ready(host) => host, + PathHost::Failed(error) => return Err(error.clone()), + _ => return Err(app.tr("render.gpu_unavailable").to_string()), + }; + let descriptor = host.descriptor().map_err(|error| error.to_string())?; + if !host.is_available() + || !descriptor.profiles.iter().any(|profile| profile.features.contains(&solidcraft_engine::render::RenderFeature::Progressive)) + { + return Err(app.tr("render.gpu_unavailable").to_string()); + } + return Ok(host); + } + let host = app.session.render_job_host().ok_or_else(|| app.tr("render.image_host_missing").to_string())?; + host.validate_integrator(if method == ImageMethod::CpuRaytrace { Integrator::Raytrace } else { Integrator::Raster }) + .map_err(|error| error.to_string())?; + Ok(host) +} + +/// Check and Start use exactly this request, rebuilt at each click. The result camera is +/// temporarily installed only inside shared navigation; app.cam remains the product camera. +fn image_params(app: &SolveApp) -> Result { + let view = &app.render_workspace.view; + image_host(app, view.method)?; + if app.session.model.is_stale() { + return Err(app.tr("render.image_scene_stale").to_string()); + } + let mut request = image_request(app)?; + if view.method == ImageMethod::CpuRaytrace && view.raytrace.progressive.is_some() { + request + .as_object_mut() + .ok_or_else(|| app.tr("render.error_provisional_identity").to_string())? + .insert("progressive_feedback".into(), json!(true)); + } + Ok(request) +} + +/// Pure request construction is shared with offline setup editing; host checks stay above. +fn image_request(app: &SolveApp) -> Result { + let request = light::filter_request(app, raw_image_request(app)?)?; + cpu_checkpoint_policy(app, request, app.render_workspace.view.raytrace.progressive.is_some()) +} + +/// One transient command flag for capture and identity, never saved setup intent. +fn cpu_checkpoint_policy(app: &SolveApp, mut request: serde_json::Value, progressive: bool) -> Result { + if app.render_workspace.view.method == ImageMethod::CpuRaytrace && progressive && !app.preferences.render_cpu_progressive_every_pass { + request + .as_object_mut() + .ok_or_else(|| app.tr("render.error_provisional_identity").to_string())? + .insert("cpu_progressive_every_pass".into(), json!(false)); + } + Ok(request) +} + +fn raw_image_request(app: &SolveApp) -> Result { + cpu::validate_progressive_image(app)?; + if !setups::has_runtime_inputs(app) { + return Ok(json!({"settings":setups::snapshot(app)?})); + } + runtime_image_request(app, false) +} + +/// CPU Interactive skips final-dimension admission and the portable snapshot path. +/// The engine fits/admit/captures this complete runtime intent off the window. +fn interactive_request(app: &SolveApp) -> Result { + if app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return Err(app.tr("render.interactive_requires_cpu").into()); + } + let request = light::filter_request(app, runtime_image_request(app, true)?)?; + // Interactive always becomes CPU progressive, including a Fixed final editor. + cpu_checkpoint_policy(app, request, true) +} + +/// The existing runtime branch, shared without changing Final Check/Start policy. +fn runtime_image_request(app: &SolveApp, interactive_cpu: bool) -> Result { + let view = &app.render_workspace.view; + // Temporary bindings and unsaved HDR captures use the runtime API. Embedded HDRs + // still resolve by their document resource ID when a temporary binding is present. + if !view.draft.surfaces.is_empty() { + return Err(app.tr("render.saved_maps_runtime_conflict").to_string()); + } + let settings = RenderSetup { camera: app.cam, job: None, ..view.draft.clone() }; + let mut params = json!({"settings":settings,"transparent_background":view.transparent}); + match view.method { + ImageMethod::Raster => {} + ImageMethod::CpuRaytrace => { + if view.transparent { + return Err(app.tr("render.cpu_opaque_required").to_string()); + } + if interactive_cpu { + cpu::params_interactive(app, &mut params)?; + } else { + cpu::params(app, &mut params)?; + } + } + ImageMethod::GpuRaytrace => { + params["progressive"] = json!(true); + params["samples"] = json!(view.samples); + params["max_depth"] = json!(view.max_depth); + params["seed"] = json!(view.seed); + studio::params(app, &mut params)?; + } + } + materials::params(app, &mut params)?; + Ok(params) +} + +fn select_image_method(app: &mut SolveApp, method: ImageMethod) { + app.render_workspace.view.method = method; + app.render_workspace.view.dirty = true; +} + +#[cfg(test)] +fn method_selector(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.label(app.tr("render.image_method")); + method_dropdown(app, ui); + if image_host(app, app.render_workspace.view.method).is_err() { + crate::ui_kit::text(ui, app.tr("render.setup_offline_help"), crate::ui_kit::Text::Note("render.setup_offline_help")); + } + if app.render_workspace.view.method != ImageMethod::Raster { + crate::ui_kit::text(ui, app.tr("render.preview_image_settings_help"), crate::ui_kit::Text::Note("render.preview_image_settings_help")); + } +} + +/// The same method authority in an aligned editor row or the legacy master form. +fn method_dropdown(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response { + let current = app.render_workspace.view.method; + let label = app.tr(current.label()).to_string(); + let response = crate::ui_kit::dropdown_menu(ui, "render_image_method", &label, |ui| { + for (method, handle) in [ + (ImageMethod::Raster, "render:method-raster"), + (ImageMethod::CpuRaytrace, "render:method-cpu"), + (ImageMethod::GpuRaytrace, "render:method-gpu"), + ] { + let capability = image_host(app, method).map(|_| ()); + let label = app.tr(method.label()).to_string(); + let response = crate::ui_kit::list_picker(ui, handle, &label, method == current); + crate::scenario::publish_handle(handle, response.rect.center()); + if response.clicked() { + select_image_method(app, method); + ui.close(); + } + if let Err(reason) = capability { + response.on_hover_text(reason); + } + } + }); + crate::scenario::publish_handle("render:method", response.rect.center()); + response +} + +fn cpu_sampling_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let progressive = cpu::progressive_controls(app, ui); + if progressive { + crate::ui_kit::text(ui, app.tr("render.cpu_progressive_help"), crate::ui_kit::Text::Note("render.cpu_progressive_help")); + } + ui.add_enabled_ui(!progressive, |ui| { + crate::ui_kit::text(ui, app.tr("render.children.edge_samples"), crate::ui_kit::Text::Inline); + let samples = app.render_workspace.view.raytrace.primary_samples; + let aa = crate::ui_kit::dropdown_menu(ui, "render_cpu_samples", &format!("{samples}×"), |ui| { + for count in [1, 4, 16] { + let handle = format!("render:aa-{count}"); + let response = crate::ui_kit::list_picker(ui, &handle, &format!("{count}×"), count == samples); + crate::scenario::publish_handle(&handle, response.rect.center()); + if response.clicked() { + app.render_workspace.view.raytrace.primary_samples = count; + ui.close(); + } + } + }); + crate::scenario::publish_handle("render:aa", aa.rect.center()); + ui.small(app.tr("render.cpu_aa_help")); + }); +} + +#[cfg(test)] +fn cpu_lighting_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.label(app.tr("render.cpu_lighting")); + let presets = [ + (LightingPreset::Neutral, "render.cpu_neutral"), + (LightingPreset::WarmCool, "render.cpu_warm_cool"), + (LightingPreset::KeyRim, "render.cpu_key_rim"), + ]; + let selected = app.render_workspace.view.raytrace.preset.unwrap_or(LightingPreset::Neutral); + let label = app + .tr(match selected { + LightingPreset::Neutral => "render.cpu_neutral", + LightingPreset::WarmCool => "render.cpu_warm_cool", + LightingPreset::KeyRim => "render.cpu_key_rim", + }) + .to_string(); + crate::ui_kit::dropdown_menu(ui, "render_cpu_lighting", &label, |ui| { + for (preset, key) in presets { + if crate::ui_kit::list_picker(ui, key, app.tr(key), preset == selected).clicked() { + app.render_workspace.view.raytrace.preset = Some(preset); + app.render_workspace.view.raytrace.lights = None; + ui.close(); + } + } + }); + let shadows = app.tr("render.cpu_shadows").to_string(); + crate::ui_kit::checkbox(ui, &shadows, &mut app.render_workspace.view.raytrace.shadows); +} + +#[cfg(test)] +fn image_method_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + method_selector(app, ui); + if app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return; + } + cpu_sampling_controls(app, ui); + cpu_lighting_controls(app, ui); + ui.label(app.tr("render.image_exposure")); + let exposure_help = app.tr("render.cpu_exposure_help").to_string(); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.exposure_ev, -32.0..=32.0, 0.1, " EV").on_hover_text(exposure_help); + cpu::controls(app, ui); +} + +#[cfg(test)] +fn image_edit_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + ui.heading(app.tr("render.image_title")); + let preview = app.tr("render.result_preview").to_string(); + let result = app.tr("render.result_title").to_string(); + let mut selected = usize::from(app.render_workspace.view.result); + if crate::ui_kit::segmented(ui, &mut selected, &[&preview, &result], crate::ui_kit::Segments { compact: true, ..Default::default() }) { + let _ = app.run("render.result.view", json!({"view":if selected == 1 {"image"} else {"model"}})); + } + if app.render_workspace.view.result { + ui.horizontal(|ui| { + if crate::ui_kit::button(ui, app.tr("render.result_fit"), crate::ui_kit::Button::Normal).clicked() { + let _ = app.run("render.result.view", json!({"view":"fit"})); + } + if crate::ui_kit::button(ui, crate::i18n::tr("render.result_actual_size"), crate::ui_kit::Button::Enabled(!reduced_display(app))) + .on_hover_text(app.tr("render.result_actual_help")) + .clicked() + { + let _ = app.run("render.result.view", json!({"view":"actual"})); + } + }); + ui.small(app.tr("render.result_navigation")); + } + image_method_controls(app, ui); + ui.small(app.tr(match app.render_workspace.view.method { + ImageMethod::Raster => "render.opaque_image_summary", + ImageMethod::CpuRaytrace => "render.cpu_summary", + ImageMethod::GpuRaytrace => "render.progressive_image_summary", + })); + // The field's hard range never silently clamps a draft when its budget changes. + let side = match app.render_workspace.view.method { + ImageMethod::CpuRaytrace => 16384, + ImageMethod::GpuRaytrace => 8192, + ImageMethod::Raster => 4096, + }; + ui.horizontal(|ui| { + ui.label(app.tr("render.image_width")); + if crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.width, 1..=side, 1.0, "").changed() { + app.render_workspace.view.dirty = true; + } + ui.label(app.tr("render.image_height")); + if crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.height, 1..=side, 1.0, "").changed() { + app.render_workspace.view.dirty = true; + } + }); + let draft = &app.render_workspace.view.draft; + let size = (u64::from(draft.width), u64::from(draft.height)); + if let Some((w, h)) = cpu::image_limits(app).fit(size.0, size.1, None) + && (w, h) != size + { + let limit = if app.render_workspace.view.method == ImageMethod::CpuRaytrace && app.render_workspace.view.raytrace.progressive.is_some() { + "render.cpu_budget_resize" + } else { + "render.image_too_large" + }; + ui.small(app.tr(limit)); + if crate::ui_kit::button(ui, format!("{} {w} × {h}", app.tr("render.image_use_largest")), crate::ui_kit::Button::Normal).clicked() { + app.render_workspace.view.draft.width = u32::try_from(w).unwrap_or(1); + app.render_workspace.view.draft.height = u32::try_from(h).unwrap_or(1); + app.render_workspace.view.dirty = true; + } + } + match &app.render_workspace.path_host { + PathHost::Preparing(_, started) => setup_progress(ui, app, *started), + PathHost::Failed(error) => { + ui.add(egui::Label::new(format!("{}: {error}", app.tr("render.gpu_path_failed"))).wrap()); + } + _ => {} + } + if app.render_workspace.view.method == ImageMethod::GpuRaytrace { + ui.label(app.tr("render.image_samples")); + // Powers of two from 1 to 4096; requests from elsewhere keep any count. + let samples = &mut app.render_workspace.view.samples; + let mut exponent = (*samples).max(1).ilog2().min(MAX_SAMPLES_EXPONENT); + let slider = crate::ui_kit::Slider { integer: true, format: |e| format!("{}", 1u32 << (e as u32).min(31)), ..Default::default() }; + if crate::ui_kit::slider(ui, &mut exponent, 0..=MAX_SAMPLES_EXPONENT, slider).changed() { + *samples = 1 << exponent.min(MAX_SAMPLES_EXPONENT); + } + let title = app.tr("render.image_advanced").to_string(); + crate::ui_kit::section(ui, "render_gpu_advanced", &title, false, |ui| { + ui.label(app.tr("render.gpu_depth")); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.max_depth, 1..=16, 1.0, ""); + ui.label(app.tr("render.gpu_seed")); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.seed, 0..=u32::MAX, 1.0, ""); + ui.label(app.tr("render.image_exposure")); + crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.exposure_ev, -32.0..=32.0, 0.1, " EV"); + ui.small(app.tr("render.gpu_options_help")); + studio::controls(app, ui); + studio::backdrop_controls(app, ui); + }); + } + library::controls(app, ui); + materials::controls(app, ui); + let transparent_label = app.tr("render.image_transparent").to_string(); + crate::ui_kit::checkbox(ui, &transparent_label, &mut app.render_workspace.view.transparent); +} + +/// Dense all-controls composition, also useful to standalone/offscreen hosts. +#[cfg(test)] +fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + image_edit_controls(app, ui); + job_controls(app, ui, false); + completed_image(app, ui); +} + +fn job_controls(app: &mut SolveApp, ui: &mut egui::Ui, compact: bool) { + let params = image_params(app); + if !compact { + if let Err(error) = ¶ms { + ui.add(egui::Label::new(egui::RichText::new(error).color(Tokens::get().warning)).wrap()); + } + cpu::checked_status(app, ui, params.as_ref().ok()); + } + let mut busy = false; + let mut state = None; + if let Some(job) = app.render_workspace.view.job { + match app.session.execute("render.status", &json!({"job":job})) { + Ok(status) => { + let phase = status["progress"]["phase"].as_str().unwrap_or(crate::i18n::tr("render.property_unknown")); + busy = matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling"); + if phase == "completed" { + app.render_workspace.view.completed = Some(job); + } + state = Some(status); + } + Err(error) => { + if !compact { + ui.add(egui::Label::new(egui::RichText::new(error.to_string()).small()).wrap()); + } + } + } + } + ui.horizontal_wrapped(|ui| { + let check = crate::ui_kit::button( + ui, + app.tr("cmd.render_preflight"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.preflight").is_ok()), + ); + crate::scenario::publish_target("render:check", check.rect); + if check.clicked() + && let Err(error) = ribbon::perform_job(app, "render.preflight") + { + app.set_status(error, true); + } + let start = crate::ui_kit::button( + ui, + app.tr("render.image_start"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.start").is_ok()), + ); + crate::scenario::publish_target("render:start", start.rect); + if start.clicked() { + if let Err(error) = ribbon::perform_job(app, "render.start") { + app.set_status(error, true); + } + ui.ctx().request_repaint(); + } + }); + let message = state.as_ref().map_or_else( + || app.tr(if params.is_ok() { "render.studio_ready" } else { "render.studio_needs_review" }).to_string(), + |status| { + app.tr(match status["progress"]["phase"].as_str().unwrap_or("") { + "queued" => "render.image_queued", + "preparing" => "render.image_preparing", + "running" => "render.image_running", + "encoding" => "render.image_encoding", + "cancelling" => "render.image_cancelling", + "cancelled" => "render.image_cancelled", + "completed" => "render.image_completed", + "failed" => "render.image_failed", + _ => "render.image_unknown", + }) + .to_string() + }, + ); + let response = ui.add_sized([ui.available_width(), ui.text_style_height(&egui::TextStyle::Body)], egui::Label::new(message).truncate()); + crate::scenario::publish_target("render:job-summary", response.rect); + if let Err(error) = ¶ms { + response.on_hover_text(error); + } + if let Some(status) = &state { + if !compact { + cpu::captured_status(app, ui, status); + if let Some(message) = status["error"]["message"].as_str() { + ui.add(egui::Label::new(egui::RichText::new(message).small()).wrap()); + } + } + if busy { + let done = status["progress"]["done"].as_u64().unwrap_or(0); + let total = status["progress"]["total"].as_u64().unwrap_or(1).max(1); + crate::ui_kit::progress(ui, "render", (done as f64 / total as f64).clamp(0.0, 1.0) as f32); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + } + } + ui.horizontal_wrapped(|ui| { + let cancel = crate::ui_kit::button( + ui, + app.tr("cmd.render_cancel"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.cancel").is_ok()), + ); + crate::scenario::publish_target("render:cancel", cancel.rect); + if cancel.clicked() + && let Err(error) = ribbon::perform_job(app, "render.cancel") + { + app.set_status(error, true); + } + let export = crate::ui_kit::button( + ui, + app.tr("render.image_export"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.export").is_ok()), + ); + crate::scenario::publish_target("render:export", export.rect); + if export.clicked() + && let Err(error) = ribbon::perform_job(app, "render.export") + { + app.set_status(error, true); + } + }); + if !compact { + let label = app.tr("render.image_overwrite").to_string(); + crate::ui_kit::checkbox(ui, &label, &mut app.render_workspace.view.overwrite); + } +} + +/// Decode each published sequence once. Provisional textures stay separate from the last +/// final image, so cancellation or a failed pass cannot change the export target. +#[cfg(test)] +fn completed_image(app: &mut SolveApp, ui: &mut egui::Ui) { + cache_render_images(app, ui.ctx()); + if let Some(display) = displayed_image(app) { + if display.provisional() { + ui.small(app.tr("render.result_provisional")); + } + match display.image { + Ok(texture) => { + if ui + .add(egui::Image::new(texture).max_size(egui::vec2(ui.available_width(), 240.0)).shrink_to_fit().sense(Sense::click())) + .on_hover_text(app.tr("render.result_open")) + .clicked() + { + let _ = app.run("render.result.view", json!({"view":"image"})); + } + } + Err(error) => { + ui.add(egui::Label::new(error).wrap()); + } + } + } else if let Some((_, Err(error))) = &app.render_workspace.image { + ui.add(egui::Label::new(error).wrap()); + } +} + +fn cache_completed_image(app: &mut SolveApp, ctx: &egui::Context) { + let Some(job) = app.render_workspace.view.completed else { + app.render_workspace.image = None; + app.render_workspace.image_info = None; + return; + }; + if app.render_workspace.image.as_ref().is_none_or(|(old, _)| *old != job) { + app.render_workspace.image_info = None; + let result = (|| -> Result { + let handle = app.session.render_job_handle(job).map_err(|e| e.to_string())?; + let frame = handle.frame().map_err(|e| e.to_string())?.ok_or(crate::i18n::tr("render.error_no_completed_image"))?; + let captured = handle.status().map_err(|e| e.to_string())?; + let budget = if frame.info.executor.as_str() == "gpu-path" { + solidcraft_engine::render::job::GPU_PATH_LIMITS + } else { + captured_image_limits(&captured.request) + }; + let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, budget, ctx.input(|i| i.max_texture_side))?; + app.session.execute("render.result.pin", &json!({"job":job})).map_err(|e| e.to_string())?; + app.render_workspace.image_info = Some(frame.info.clone()); + Ok(ctx.load_texture("sc_render_image", image, egui::TextureOptions::LINEAR)) + })(); + // Cache errors too, so a bad frame cannot repeatedly allocate or decode on repaint. + app.render_workspace.image = Some((job, result)); + } +} + +fn displayed_image(app: &SolveApp) -> Option> { + let state = &app.render_workspace; + let preview = state.preview_image.as_ref().filter(|image| state.view.job == Some(image.info.frame.job)); + let partial = state.final_partial.as_ref().filter(|image| state.view.job == Some(image.info.frame.job)); + if let Some(partial) = partial { + let pixels = u64::from(partial.info.source_width) * u64::from(partial.info.source_height); + let frontier = u64::from(partial.info.completed_passes) * pixels + partial.info.updated_prefix; + // Complete-pass and partial sequence numbers have different namespaces. + // Equal source evidence prefers the established complete-pass image. + if preview.is_none_or(|image| u64::from(image.info.samples_per_pixel) * pixels < frontier) { + return Some(DisplayImage { + info: &partial.info.frame, + image: &partial.image, + preview: None, + partial: Some((&partial.info, partial.sampling)), + logical_size: [partial.info.source_width, partial.info.source_height], + }); + } + } + if let Some(preview) = preview { + return Some(DisplayImage { + info: &preview.info.frame, + image: &preview.image, + preview: Some(&preview.info), + partial: None, + logical_size: [preview.info.frame.width, preview.info.frame.height], + }); + } + let info = state.image_info.as_ref()?; + Some(DisplayImage { info, image: &state.image.as_ref()?.1, preview: None, partial: None, logical_size: [info.width, info.height] }) +} + +fn cache_final_partial( + app: &mut SolveApp, + ctx: &egui::Context, + handle: &solidcraft_engine::render::job::JobHandle, + status: &solidcraft_engine::render::job::JobStatus, + partial: &solidcraft_engine::render::job::RenderPartialPreview, +) -> Result<(), String> { + let job = handle.id(); + if app.render_workspace.view.job != Some(job) { + return Ok(()); + } + let previous = app.render_workspace.final_partial.as_ref().filter(|cached| cached.info.frame.job == job).map(|cached| cached.sampling); + let expected = interactive::PartialExpectation { + job, + scene_generation: status.scene_generation, + request: &status.request, + final_dimensions: [status.request.width, status.request.height], + }; + let Some(sampling) = interactive::validate_partial_metadata(&expected, &partial.info, partial.png().len(), partial.covered().len(), previous)? + else { + return Ok(()); + }; + let image = interactive::decode_partial_image( + &status.request, + &partial.info, + partial.png(), + partial.covered(), + sampling, + ctx.input(|input| input.max_texture_side), + ) + .map(|pixels| ctx.load_texture("sc_render_final_partial", pixels, egui::TextureOptions::NEAREST)); + if app.render_workspace.view.job == Some(job) { + app.render_workspace.final_partial = Some(FinalPartialImage { info: partial.info.clone(), sampling, image }); + } + // Only texture/provenance survives: the borrowed PNG/coverage/lease is not retained. + Ok(()) +} + +fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewInfo, png: &[u8]) { + if app.render_workspace.view.job != Some(info.frame.job) { + return; + } + if app + .render_workspace + .preview_image + .as_ref() + .is_some_and(|old| old.info.frame.job == info.frame.job && old.info.frame_sequence >= info.frame_sequence) + { + return; + } + let result = (|| -> Result { + if info.frame_sequence == 0 || !(1..=solidcraft_engine::render::job::MAX_CPU_SAMPLES_PER_PIXEL).contains(&info.samples_per_pixel) { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + let handle = app.session.render_job_handle(info.frame.job).map_err(|e| e.to_string())?; + let captured = handle.status().map_err(|e| e.to_string())?; + if captured + .request + .raytrace + .as_ref() + .and_then(|options| options.progressive) + .is_some_and(|target| info.samples_per_pixel > target.samples_per_pixel) + { + return Err(crate::i18n::tr("render.error_provisional_identity").into()); + } + if (info.frame.width, info.frame.height) != (captured.request.width, captured.request.height) { + return Err(crate::i18n::tr("render.error_checkpoint_dimensions").into()); + } + let options = solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: info.samples_per_pixel, seed: 0 }; + options.validate_image_with_budget(info.frame.width, info.frame.height, captured.request.cpu_budget()).map_err(|error| error.to_string())?; + let image = decode_render_image( + png, + info.frame.width, + info.frame.height, + captured_image_limits(&captured.request), + ctx.input(|i| i.max_texture_side), + )?; + Ok(ctx.load_texture("sc_render_preview", image, egui::TextureOptions::LINEAR)) + })(); + // Cache errors by identity too: a malformed publication cannot decode on every repaint. + app.render_workspace.preview_image = Some(PreviewImage { info: info.clone(), image: result }); +} + +// Consumer-only reconciliation of a temporarily absent latest publication. +// Status must come from the actual handle; retained pixels never imply new work. +fn reconcile_missing_cpu_preview(state: &mut State, job: JobId, status: Option<&solidcraft_engine::render::job::JobStatus>) { + let retain = state.preview_image.as_ref().is_some_and(|cached| { + cached.image.is_ok() + && status.is_some_and(|current| { + current.job == job + && cached.info.frame.job == current.job + && cached.info.frame.scene_generation == current.scene_generation + && (cached.info.frame.width, cached.info.frame.height) == (current.request.width, current.request.height) + && current.request.integrator == Integrator::Raytrace + && current.request.raytrace.as_ref().is_some_and(|options| options.progressive.is_some()) + && current.cpu_preview_retention_skips > 0 + && !current.progress.phase.terminal() + && current.progress.phase != solidcraft_engine::render::job::Phase::Cancelling + && current.error.is_none() + && current.frame.is_none() + }) + }); + if !retain { + state.preview_image = None; + } +} + +fn cache_preview_image(app: &mut SolveApp, ctx: &egui::Context) { + if let Some(job) = app.render_workspace.view.job + && let Ok(handle) = app.session.render_job_handle(job) + && let Ok(status) = handle.status() + { + if app.render_workspace.final_partial.as_ref().is_some_and(|cached| cached.info.frame.job != job) { + app.render_workspace.final_partial = None; + } + let now = interactive::monotonic(app.render_workspace.final_feedback_clock, ctx.input(|input| input.time)); + app.render_workspace.final_feedback_clock = now; + if !status.progress.phase.terminal() + && status.request.integrator == Integrator::Raytrace + && status.request.raytrace.as_ref().and_then(|options| options.progressive).is_some() + && interactive::partial_request_due(app.render_workspace.final_partial_request, job, now) + { + app.render_workspace.final_partial_request = Some((job, now)); + if let Err(error) = handle.request_partial_preview() { + app.set_status(error.to_string(), true); + } + } + app.render_workspace.final_feedback_report = handle.protected_preview_report().ok().flatten().map(|report| (job, report)); + let preview = handle.preview().ok().flatten(); + let partial = handle.partial_preview().ok().flatten(); + // Read completion AFTER both provisional slots: neither can be promoted to a final. + if handle.frame().ok().flatten().is_some() { + app.render_workspace.view.completed = Some(job); + } else if !status.progress.phase.terminal() { + if let Some(preview) = preview { + cache_preview_frame(app, ctx, &preview.info, preview.png()); + } else { + // Re-read after observing None: the producer may have certified + // a retention skip after the earlier status snapshot. + let current = handle.status().ok(); + reconcile_missing_cpu_preview(&mut app.render_workspace, job, current.as_ref()); + } + if let Some(partial) = partial + && let Err(error) = cache_final_partial(app, ctx, &handle, &status, &partial) + { + app.set_status(error, true); + } + // Decoding can race final publication/cancellation. Recheck the real job. + if handle.frame().ok().flatten().is_some() { + app.render_workspace.view.completed = Some(job); + } else if final_job_still_running(app, &handle) { + return; + } + } + } else { + app.render_workspace.final_feedback_report = None; + } + app.render_workspace.preview_image = None; + app.render_workspace.final_partial = None; +} + +/// Reconcile a terminal observation made after a frame read returned None. +/// Complete publishes its real frame under the same host data lock; read that +/// frame again before the caller clears provisional caches or falls back. +fn final_job_still_running(app: &mut SolveApp, handle: &solidcraft_engine::render::job::JobHandle) -> bool { + let job = handle.id(); + if app.render_workspace.view.job != Some(job) { + return false; + } + let status = match handle.status() { + Ok(status) => status, + Err(error) => { + app.set_status(error.to_string(), true); + return false; + } + }; + if status.progress.phase == solidcraft_engine::render::job::Phase::Completed { + match handle.frame() { + Ok(Some(frame)) if app.render_workspace.view.job == Some(frame.info.job) => { + app.render_workspace.view.completed = Some(frame.info.job); + } + Err(error) => app.set_status(error.to_string(), true), + _ => {} + } + return false; + } + !status.progress.phase.terminal() +} + +fn remember_displayed_job(app: &mut SolveApp, preserve_view: bool) { + let Some(job) = displayed_image(app).map(|display| display.info.job) else { return }; + if app.render_workspace.view.result_job != Some(job) { + app.render_workspace.view.result_job = Some(job); + if !preserve_view { + app.render_workspace.view.result_scale = ResultScale::Fit; + } + } +} + +fn cache_render_images(app: &mut SolveApp, ctx: &egui::Context) { + let preserve_view = displayed_image(app).is_some_and(|display| { + display.provisional() + && app.render_workspace.view.result_job == Some(display.info.job) + && app.render_workspace.view.job == Some(display.info.job) + }); + cache_preview_image(app, ctx); + cache_completed_image(app, ctx); + // Checkpoint updates and preview→final/cancel transitions preserve shared pan/zoom. + remember_displayed_job(app, preserve_view); +} + +fn captured_image_limits(request: &solidcraft_engine::render::job::ImageRequest) -> RenderLimits { + if request.integrator == Integrator::Raytrace { + request.cpu_budget().image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())) + } else { + RenderLimits::default() + } +} + +/// This is a display cache only: the authoritative PNG/frame and export remain +/// full resolution. Avoid asking a viewport device for an unsupported texture. +fn display_dimensions(width: u32, height: u32, max_texture_side: usize) -> Result<(u32, u32), String> { + if width == 0 || height == 0 || max_texture_side == 0 { + return Err(crate::i18n::tr("render.error_display_dimensions").into()); + } + let max_side = max_texture_side.min(8192) as u64; + let display = RenderLimits { max_dimension: max_side, max_pixels: 16_777_216, max_scratch_bytes: 512 * 1024 * 1024 }; + let (w, h) = display.fit(u64::from(width), u64::from(height), None).ok_or(crate::i18n::tr("render.error_display_fit"))?; + Ok(( + u32::try_from(w).map_err(|_| crate::i18n::tr("render.error_display_width"))?, + u32::try_from(h).map_err(|_| crate::i18n::tr("render.error_display_height"))?, + )) +} + +#[cfg(test)] +fn decode_image(png: &[u8], width: u32, height: u32) -> Result { + decode_render_image(png, width, height, RenderLimits::default(), 8192) +} + +fn decode_render_image(png: &[u8], width: u32, height: u32, budget: RenderLimits, max_texture_side: usize) -> Result { + let size = (u64::from(width), u64::from(height)); + if budget.fit(size.0, size.1, None) != Some(size) { + return Err(crate::i18n::tr("render.error_image_profile").into()); + } + let display_size = display_dimensions(width, height, max_texture_side)?; + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(width); + limits.max_image_height = Some(height); + limits.max_alloc = Some(size.0.checked_mul(size.1).and_then(|n| n.checked_mul(16)).ok_or(crate::i18n::tr("render.error_decode_budget"))?); + reader.limits(limits); + let image = reader.decode().map_err(|e| e.to_string())?.to_rgba8(); + if image.dimensions() != (width, height) { + return Err(crate::i18n::tr("render.error_image_dimensions").into()); + } + let image = if display_size != (width, height) { + image::imageops::resize(&image, display_size.0, display_size.1, image::imageops::FilterType::Triangle) + } else { + image + }; + Ok(egui::ColorImage::from_rgba_unmultiplied([display_size.0 as usize, display_size.1 as usize], image.as_raw())) +} + +fn reduced_display(app: &SolveApp) -> bool { + displayed_image(app).is_some_and(|display| { + display.image.as_ref().is_ok_and(|texture| texture.size() != [display.logical_size[0] as usize, display.logical_size[1] as usize]) + }) +} + +/// The image has its own per-document orthographic camera. Shared navigation can temporarily +/// drive it without changing the product camera, saved setup, or a pending Design view. +pub(crate) fn with_result_camera(app: &mut SolveApp, navigate: impl FnOnce(&mut SolveApp)) { + let preview = std::mem::replace(&mut app.cam, app.render_workspace.view.result_camera); + let before = app.cam; + let draft = app.render_workspace.view.draft.clone(); + let dirty = app.render_workspace.view.dirty; + let perspective = std::mem::replace(&mut app.ui.perspective, false); + let up = app.ui.up_axis; + let animation = app.cam_anim.take(); + let pending = app.pending_fit.take(); + let request = app.session.camera.take(); + let free = app.viewport.orbit_free.take(); + let spin = std::mem::replace(&mut app.viewport.spin, false); + navigate(app); + app.render_workspace.view.result_camera = std::mem::replace(&mut app.cam, preview); + if app.render_workspace.view.result_camera != before { + app.render_workspace.view.result_scale = ResultScale::Free; + } + app.render_workspace.view.draft = draft; + app.render_workspace.view.dirty = dirty; + app.ui.perspective = perspective; + app.ui.up_axis = up; + app.cam_anim = animation; + app.pending_fit = pending; + app.session.camera = request; + app.viewport.orbit_free = free; + app.viewport.spin = spin; +} + +fn result_camera(size: [u32; 2], rect: egui::Rect, pixels_per_point: f32, scale: ResultScale) -> Camera { + let width = f64::from(size[0].max(1)); + let height = f64::from(size[1].max(1)); + let scale = if scale == ResultScale::Actual { + 1.0 / f64::from(pixels_per_point.max(0.1)) + } else { + (f64::from((rect.width() - 32.0).max(1.0)) / width).min(f64::from((rect.height() - 32.0).max(1.0)) / height) + }; + Camera { + yaw: 0.0, + pitch: std::f64::consts::FRAC_PI_2, + distance: (f64::from(rect.height().max(1.0)) / (0.8 * scale)).clamp(1e-3, 1e7), + ..Default::default() + } +} + +fn result_rect(camera: Camera, size: [u32; 2], canvas: egui::Rect) -> egui::Rect { + let scale = f64::from(canvas.height().max(1.0)) / (2.0 * camera.half_height()); + let center = canvas.center() + egui::vec2((-camera.target.x * scale) as f32, (camera.target.y * scale) as f32); + egui::Rect::from_center_size(center, egui::vec2((f64::from(size[0]) * scale) as f32, (f64::from(size[1]) * scale) as f32)) +} + +fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { + for (view, key) in [("model", "render.state_model"), ("fit", "render.output_fit"), ("actual", "render.result_actual")] { + let enabled = view != "actual" || !reduced_display(app); + if crate::ui_kit::button(ui, app.tr(key), crate::ui_kit::Button::Enabled(enabled)).clicked() { + let _ = app.run("render.result.view", json!({"view":view})); + } + } + let copy = crate::ui_kit::button( + ui, + app.tr("render.output_copy"), + crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.result.copy").is_ok()), + ); + crate::scenario::publish_target("render:result-copy", copy.rect); + if copy.clicked() { + app.start("render.result.copy"); + } + let export = + crate::ui_kit::button(ui, studio::export_label(app), crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.export").is_ok())); + crate::scenario::publish_target("render:result-export", export.rect); + if export.clicked() { + app.start("render.export"); + } + let close = crate::ui_kit::StageBar::icon_action(ui, "close", app.tr("cmd.render_result_close")); + crate::scenario::publish_target("render:result-close", close.rect); + if close.clicked() { + app.start("render.result.close"); + } +} + +fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { + cache_render_images(app, ui.ctx()); + let t = Tokens::get(); + ui.painter().rect_filled(ui.max_rect(), 0.0, t.viewport_bottom); + // The floating shell paints after this canvas. Keep image actions in its free + // content area so neither ribbon nor Browser can cover their hit targets. + let mut free = crate::render_ui::canvas(app, ui.max_rect()); + if ribbon::busy(app) { + free = crate::ui_kit::Container::below_navigation_row(free); + } + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_result_content")); + let ui = &mut content; + let Some((info, preview, partial, logical_size)) = displayed_image(app).map(|display| { + (display.info.clone(), display.preview.cloned(), display.partial.map(|(info, sampling)| (info.clone(), sampling)), display.logical_size) + }) else { + let message = match &app.render_workspace.image { + Some((_, Err(error))) => error.clone(), + _ if ribbon::busy(app) => app.tr("render.state_in_progress").to_string(), + _ => app.tr("render.result_empty").to_string(), + }; + crate::ui_kit::Container::navigation_contents(ui, |ui| { + ui.horizontal_wrapped(|ui| { + crate::ui_kit::text( + ui, + app.tr(if ribbon::busy(app) { "render.state_in_progress" } else { "render.result_title" }), + crate::ui_kit::Text::Inline, + ); + result_actions(app, ui); + }); + }); + let canvas = ui.available_rect_before_wrap(); + ui.centered_and_justified(|ui| { + ui.add(egui::Label::new(egui::RichText::new(message).size(t.font_heading).color(t.text)).wrap()); + }); + app.viewport.rect = Some(canvas); + return; + }; + crate::ui_kit::Container::navigation_contents(ui, |ui| { + ui.horizontal_wrapped(|ui| { + crate::ui_kit::text( + ui, + app.tr(if preview.is_some() || partial.is_some() { "render.state_in_progress" } else { "render.state_completed" }), + crate::ui_kit::Text::Inline, + ); + result_actions(app, ui); + }); + if let Some(preview) = &preview { + ui.colored_label( + t.warning, + format!( + "{} · {} {} · {} {}", + app.tr("render.result_provisional"), + preview.samples_per_pixel, + app.tr("render.cpu_progressive_spp"), + app.tr("render.result_sequence"), + preview.frame_sequence + ), + ); + if let Ok(handle) = app.session.render_job_handle(preview.frame.job) + && let Ok(status) = handle.status() + && let Some(target) = status.request.raytrace.as_ref().and_then(|options| options.progressive) + { + ui.small(crate::i18n::format( + "render.cpu_pass_progress", + &[("current", &preview.samples_per_pixel.to_string()), ("target", &target.samples_per_pixel.to_string())], + )); + } + ui.small(app.tr("render.result_provisional_help")); + } + if let Some((info, sampling)) = &partial { + ui.colored_label(t.warning, app.tr("render.result_provisional")); + if let Ok(handle) = app.session.render_job_handle(info.frame.job) + && let Ok(status) = handle.status() + && let Some(target) = status.request.raytrace.as_ref().and_then(|options| options.progressive) + { + ui.small(crate::i18n::format( + "render.cpu_pass_progress", + &[("current", &info.completed_passes.to_string()), ("target", &target.samples_per_pixel.to_string())], + )); + } + let (min, max) = sampling.sample_range(); + ui.small(crate::i18n::format( + "render.interactive_partial_samples", + &[ + ("min", &min.to_string()), + ("max", &max.to_string()), + ("known", &sampling.sampled_source_pixels().to_string()), + ("pixels", &(u64::from(info.source_width) * u64::from(info.source_height)).to_string()), + ], + )); + ui.small(crate::i18n::format( + "render.interactive_partial_dimensions", + &[ + ("display_width", &info.frame.width.to_string()), + ("display_height", &info.frame.height.to_string()), + ("source_width", &info.source_width.to_string()), + ("source_height", &info.source_height.to_string()), + ("final_width", &logical_size[0].to_string()), + ("final_height", &logical_size[1].to_string()), + ], + )); + ui.small(app.tr("render.result_provisional_help")); + } + if let Some((job, report)) = app.render_workspace.final_feedback_report + && job == info.job + && (preview.is_some() || partial.is_some()) + { + ui.small(crate::i18n::format( + "render.interactive_feedback_usage", + &[("started", &report.accepted_snapshots.to_string()), ("limit", &report.quota_limit.to_string())], + )); + let reason = if report.quota_exhausted { + Some("render.interactive_feedback_quota_exhausted") + } else if report.milestones_complete { + Some("render.interactive_feedback_milestones_complete") + } else { + None + }; + if let Some(reason) = reason { + ui.small(app.tr(reason)); + } + } + if let Some(display) = displayed_image(app) + && let Err(error) = display.image + { + ui.colored_label(t.warning, error); + } + ui.horizontal_wrapped(|ui| { + ui.strong(format!("{} × {} px · PNG · {}", logical_size[0], logical_size[1], info.executor.as_str())); + ui.label(format!( + "{} {}:{}:{} · {} {}", + app.tr("render.result_job"), + info.job.session, + info.job.serial, + info.job.generation, + app.tr("render.result_capture"), + info.scene_generation + )); + }); + if reduced_display(app) { + ui.colored_label(t.warning, app.tr("render.result_reduced_display")); + } + let stale = info.scene_generation != app.session.revision; + ui.colored_label(if stale { t.warning } else { t.text_dim }, app.tr(if stale { "render.image_stale" } else { "render.result_current" })); + if app.render_workspace.view.job.is_some_and(|job| job != info.job) { + ui.small(app.tr("render.result_retained")); + } + }); + let rect = ui.available_rect_before_wrap(); + if rect.width() < 1.0 || rect.height() < 1.0 { + return; + } + let response = ui.allocate_rect(rect, Sense::click_and_drag()); + app.viewport.rect = Some(rect); + crate::viewport::refresh_layout(app, ui.ctx()); + let size = logical_size; + let scale = app.render_workspace.view.result_scale; + if scale != ResultScale::Free { + app.render_workspace.view.result_camera = result_camera(size, rect, ui.ctx().pixels_per_point(), scale); + } + with_result_camera(app, |app| { + crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps { orbit: false, pick: false }); + }); + let after = app.render_workspace.view.result_scale; + if after != scale && after != ResultScale::Free { + app.render_workspace.view.result_camera = result_camera(size, rect, ui.ctx().pixels_per_point(), after); + } + let camera = app.render_workspace.view.result_camera; + let mut image_rect = result_rect(camera, size, rect); + if after == ResultScale::Actual { + let dpi = ui.ctx().pixels_per_point(); + let min = egui::pos2((image_rect.min.x * dpi).round() / dpi, (image_rect.min.y * dpi).round() / dpi); + image_rect = image_rect.translate(min - image_rect.min); + } + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + let visible = image_rect.intersect(rect); + if visible.is_positive() { + // Bound checker work by the visible canvas, even for an extremely magnified image. + painter.rect_filled(visible, 0.0, t.panel); + let cell = 24.0f32.max(visible.width().max(visible.height()) / 128.0); + for row in 0..(visible.height() / cell).ceil() as u32 { + for column in 0..(visible.width() / cell).ceil() as u32 { + if (row + column) % 2 == 0 { + let square = egui::Rect::from_min_size(visible.min + egui::vec2(column as f32 * cell, row as f32 * cell), egui::vec2(cell, cell)); + painter.rect_filled(square.intersect(visible), 0.0, t.control_fill); + } + } + } + if let Some(display) = displayed_image(app) + && let Ok(texture) = display.image + { + painter.image(texture.id(), image_rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Tokens::get().file_image_tint); + } + painter.rect_stroke(image_rect, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Outside); + } + let percent = f64::from(rect.height() * ui.ctx().pixels_per_point()) / (2.0 * camera.half_height()) * 100.0; + let label = painter.layout_no_wrap(format!("{percent:.1}%"), egui::FontId::proportional(t.font_label), t.text); + let badge = egui::Rect::from_min_size( + rect.left_bottom() + egui::vec2(t.space_8, -label.size().y - t.space_8 * 2.0), + label.size() + egui::vec2(t.space_8 * 2.0, t.space_8), + ); + painter.rect_filled(badge, t.control_radius, t.panel); + painter.galley(badge.min + egui::vec2(t.space_8, t.space_8 * 0.5), label, t.text); + crate::navigation_bar_view::show(app, ui, rect); +} + +impl State { + fn prepare_preview(&mut self, signature: (u64, usize, u64, u64), capture: impl FnOnce() -> Result) -> Result<(), String> { + if self.scene_signature != Some(signature) { + let prepared = capture().and_then(|scene| gpu_scene_with_budget(&scene, signature.3).map(|(key, gpu)| (scene, key, gpu))); + self.scene_signature = Some(signature); + match prepared { + Ok((scene, key, gpu)) => { + let bytes = gpu.pbr.len() + gpu.tris.len() + gpu.glass.len(); + if self.key != Some(key) { + let uploaded = match self.slot.lock() { + Ok(mut slot) => { + *slot = Some(gpu); + true + } + Err(_) => false, + }; + if !uploaded { + let error = crate::i18n::tr("render.error_upload_slot").to_string(); + self.scene = None; + self.key = None; + self.preview_upload_bytes = None; + self.scene_error = Some(error.clone()); + return Err(error); + } + self.key = Some(key); + if let Ok(mut error) = self.upload_error.lock() { + *error = None; + } + } + self.scene = Some(scene); + self.scene_error = None; + self.preview_upload_bytes = Some(bytes); + } + Err(error) => { + self.scene = None; + self.key = None; + self.preview_upload_bytes = None; + if let Ok(mut slot) = self.slot.lock() { + *slot = None; + } + self.scene_error = Some(error); + } + } + } + match &self.scene_error { + Some(error) => Err(error.clone()), + None => Ok(()), + } + } +} + +/// Use the shared kit's wrapped, themed error surface, not text painted directly +/// on the user-selected background (which may have the opposite theme contrast). +fn preview_error(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, error: &str) { + let t = Tokens::get(); + let bounded = crate::shell::workspace_content(app, crate::shell::panel_bounds(app, rect)).shrink(t.space_12); + // At tiny window sizes the shell may leave no room for the shared error card. + if !bounded.is_finite() || bounded.width() < t.control_height + 2.0 * t.space_8 || bounded.height() < t.control_height + 2.0 * t.space_8 { + return; + } + ui.scope_builder(egui::UiBuilder::new().max_rect(bounded), |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(bounded)); + ui.set_max_width(bounded.width().min(t.form_card_width * 2.0)); + crate::ui_kit::Panel::feature_frame(ui.ctx(), crate::shell::LayoutMode::Floating, crate::frame::Side::Left).inner_margin(t.space_8).show( + ui, + |ui| { + crate::ui_kit::text(ui, error, crate::ui_kit::Text::Error("render.preview_failure")); + crate::ui_kit::text(ui, app.tr("render.preview_unavailable_help"), crate::ui_kit::Text::Note("render.preview_unavailable_help")); + let retry = crate::ui_kit::button(ui, app.tr("render.preview_retry"), crate::ui_kit::Button::Normal); + crate::scenario::publish_target("render:preview-retry", retry.rect); + if retry.clicked() { + invalidate_scene(app); + ui.ctx().request_repaint(); + } + }, + ); + }); +} + +/// Keep the selected image and overwrite consent fixed while the upstream picker holds model input. +fn export_image(app: &mut SolveApp, job: solidcraft_engine::render::job::JobId, overwrite: bool) { + let origin = app.session.doc.clone(); + app.pick_save("render.png", &["png"], move |app, path| { + let Some(path) = path else { return }; + if !Arc::ptr_eq(&origin, &app.session.doc) { + app.set_status(crate::i18n::tr("render.error_export_document"), true); + return; + } + let _ = app.run("render.export", json!({"job":job,"path":path,"overwrite":overwrite})); + }); +} + +/// Captures format and completed identity before the asynchronous picker opens. +fn export_linear_image(app: &mut SolveApp, job: solidcraft_engine::render::job::JobId, overwrite: bool) { + let origin = app.session.doc.clone(); + app.pick_save("render.exr", &["exr"], move |app, path| { + let Some(path) = path else { + return; + }; + if !Arc::ptr_eq(&origin, &app.session.doc) { + app.set_status(crate::i18n::tr("render.error_export_document"), true); + return; + } + let _ = app.run("render.export", json!({"job":job,"path":path,"overwrite":overwrite,"format":"exr"})); + }); +} + +/// An exact expanded vertex payload, counted before allocating its buffers. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct PreviewUploadPlan { + pbr: usize, + tris: usize, + glass: usize, + source_triangles: usize, +} +impl PreviewUploadPlan { + fn bytes(self) -> Result { + self.pbr.checked_add(self.tris).and_then(|n| n.checked_add(self.glass)).ok_or_else(|| crate::i18n::tr("render.error_geometry_size").into()) + } + fn add(&mut self, pbr: bool, glass: bool, triangles: usize, limit: usize) -> Result<(), String> { + let stride = if pbr { crate::gpu::PBR_SIZE } else { crate::gpu::TRI_SIZE }; + let bytes = triangles.checked_mul(3).and_then(|n| n.checked_mul(stride)).ok_or(crate::i18n::tr("render.error_geometry_size"))?; + let count = if pbr { + &mut self.pbr + } else if glass { + &mut self.glass + } else { + &mut self.tris + }; + *count = count.checked_add(bytes).ok_or(crate::i18n::tr("render.error_geometry_size"))?; + admit_geometry(self.bytes()? as u64, limit as u64) + } +} + +fn preview_upload_plan(scene: &ProductScene, limit: usize) -> Result { + if scene.meshes.len() > solidcraft_engine::render::job::MAX_CPU_BODIES { + return Err(crate::i18n::tr("render.error_body_bound").into()); + } + let mut plan = PreviewUploadPlan::default(); + for body in &scene.meshes { + plan.source_triangles = plan.source_triangles.checked_add(body.mesh.triangles.len()).ok_or(crate::i18n::tr("render.error_triangle_count"))?; + if plan.source_triangles > solidcraft_engine::render::job::MAX_CPU_TRIANGLES { + return Err(crate::i18n::tr("render.error_triangle_bound").into()); + } + if body.faces.len() > 262_144 { + return Err(crate::i18n::tr("render.error_face_cap").into()); + } + if !body.opacity.is_finite() + || !(0.0..=1.0).contains(&body.opacity) + || body.faces.iter().any(|face| !face.opacity.is_finite() || !(0.0..=1.0).contains(&face.opacity)) + { + return Err(crate::i18n::tr("render.error_opacity").into()); + } + let looks: std::collections::BTreeMap<_, _> = body.faces.iter().map(|face| (face.face, face)).collect(); + if looks.len() != body.faces.len() { + return Err(crate::i18n::tr("render.error_duplicate_face").into()); + } + for index in 0..body.mesh.triangles.len() { + let face = body.mesh.tri_face.get(index).and_then(|id| looks.get(id)); + let (opacity, pbr) = face.map_or((body.opacity, body.surface.is_some() && body.transmission.is_none()), |face| { + (face.opacity, face.surface.is_some() && face.transmission.is_none()) + }); + if pbr && opacity != 1.0 { + return Err(crate::i18n::tr("render.error_pbr_opacity").into()); + } + if opacity > 0.0 { + plan.add(pbr, opacity < 0.999, 1, usize::MAX)?; + } + } + } + admit_geometry(plan.bytes()? as u64, limit as u64)?; + Ok(plan) +} + +/// Convert all captured surfaces, without decimation. The finite, exact payload +/// plan is admitted first; each output vector is reserved once rather than grown +/// once per triangle. Device uploads retain their existing chunked buffer path. +#[cfg(test)] +fn gpu_scene(scene: &ProductScene) -> Result<(u64, GpuScene), String> { + gpu_scene_with_budget(scene, MAX_GEOMETRY_BYTES as u64) +} + +fn gpu_scene_with_budget(scene: &ProductScene, budget: u64) -> Result<(u64, GpuScene), String> { + let limit = usize::try_from(budget).unwrap_or(usize::MAX); + let plan = preview_upload_plan(scene, limit)?; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + let mut gpu = GpuScene::default(); + for (buffer, bytes) in [(&mut gpu.pbr, plan.pbr), (&mut gpu.tris, plan.tris), (&mut gpu.glass, plan.glass)] { + buffer.try_reserve_exact(bytes).map_err(|_| crate::i18n::tr("render.error_vertex_allocation").to_string())?; + } + for body in &scene.meshes { + if body.faces.len() > 262_144 { + return Err(crate::i18n::tr("render.error_face_cap").into()); + } + if !body.opacity.is_finite() + || !(0.0..=1.0).contains(&body.opacity) + || body.faces.iter().any(|f| !f.opacity.is_finite() || !(0.0..=1.0).contains(&f.opacity)) + { + return Err(crate::i18n::tr("render.error_opacity").into()); + } + (Arc::as_ptr(&body.mesh) as usize).hash(&mut hash); + body.name.hash(&mut hash); + body.color.hash(&mut hash); + body.opacity.to_bits().hash(&mut hash); + body.transmission.is_some().hash(&mut hash); + hash_surface(body.surface, &mut hash); + let looks: std::collections::BTreeMap<_, _> = body.faces.iter().map(|l| (l.face, l)).collect(); + for face in &body.faces { + face.face.hash(&mut hash); + face.color.hash(&mut hash); + face.opacity.to_bits().hash(&mut hash); + face.transmission.is_some().hash(&mut hash); + hash_surface(face.surface, &mut hash); + } + for (index, triangle) in body.mesh.triangles.iter().enumerate() { + let face = body.mesh.tri_face.get(index).and_then(|f| looks.get(f)); + let (color, opacity, surface) = face.map_or((body.color, body.opacity, body.surface.filter(|_| body.transmission.is_none())), |l| { + (l.color, l.opacity, l.surface.filter(|_| l.transmission.is_none())) + }); + if surface.is_some() && opacity != 1.0 { + return Err(crate::i18n::tr("render.error_pbr_opacity").into()); + } + if opacity <= 0.0 { + continue; + } + let vertices = triangle.map(|i| { + let p = body.mesh.positions.get(i as usize)?.to_f32(); + let n = *body.mesh.normals.get(i as usize)?; + let n = if surface.is_some() { solidcraft_engine::render::surface::unit_direction(n).ok()? } else { n }.to_f32(); + p.into_iter().chain(n).all(f32::is_finite).then_some((p, n)) + }); + let [Some(a), Some(b), Some(c)] = vertices else { return Err(crate::i18n::tr("render.error_product_triangle").into()) }; + let rgba = [color[0], color[1], color[2], (opacity * 255.0).round() as u8]; + let index = gpu.color(rgba); + for (p, n) in [a, b, c] { + if let Some(surface) = surface { + if n.iter().all(|v| *v == 0.0) { + return Err(crate::i18n::tr("render.error_surface_normals").into()); + } + gpu.pbr_tri(p, n, surface); + } else if opacity < 0.999 { + gpu.glass_tri(p, n, index); + } else { + gpu.tri(p, n, index); + } + } + } + } + if (gpu.pbr.len(), gpu.tris.len(), gpu.glass.len()) != (plan.pbr, plan.tris, plan.glass) { + return Err(crate::i18n::tr("render.error_vertex_packing").into()); + } + Ok((hash.finish(), gpu)) +} + +fn hash_surface(surface: Option, hash: &mut impl Hasher) { + surface.is_some().hash(hash); + if let Some(s) = surface { + let c = s.base_color(); + for value in [c.x, c.y, c.z, s.metallic(), s.roughness(), s.dielectric_ior()] { + value.to_bits().hash(hash); + } + } +} + +/// The size the product preview draws at for a viewport of `full` physical pixels: the full +/// size when the viewport executor admits it, else the largest size at the same aspect it does. +/// Without an executor the request is left for resolution to report. +pub fn preview_size(executor: Option<&ExecutorDescriptor>, full: (u64, u64)) -> (u64, u64) { + executor.and_then(|e| e.fit(full.0, full.1)).unwrap_or(full) +} + +/// Model Preview presents the common exposure regardless of the selected final method. +/// Already captured Interactive and Result pixels return before this product-frame path. +fn product_preview_exposure(app: &SolveApp) -> Result { + solidcraft_gpu::view::ProductExposureEv::from_ev(app.render_workspace.view.draft.exposure_ev) + .ok_or_else(|| app.tr("render.product_exposure_invalid").to_string()) +} + +pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.render_workspace.view.result { + interactive::before_paint(app, ui.ctx()); + app.render_workspace.view.environment_ring = environment::RingView::default(); + assign::stop(app); + show_result(app, ui); + return; + } + let viewport = ui.max_rect(); + app.viewport.rect = Some(viewport); + // Framing uses the output camera's own aspect, including navigation and picking. + let rect = shot::preview_rect(app, viewport).unwrap_or(viewport); + crate::viewport::refresh_layout(app, ui.ctx()); + let response = ui.interact(rect, ui.id().with("render_preview"), Sense::click_and_drag()); + if !environment::ring_input(app, ui, rect, &response) { + let input = crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps::RENDER); + // Navigation can invalidate the displayed image in this frame. Observe before + // any geometry interaction, and observe again below after visible UI actions. + interactive::before_paint(app, ui.ctx()); + let waiting = interactive::blocks_geometry_input(app); + let geometry_rect = interactive::geometry_input_rect(app, rect); + let geometry_inside = input.inside && input.hover.is_some_and(|pos| geometry_rect.contains(pos)); + let navigating = input.scroll != 0.0 + || input.pinch != 1.0 + || input.pan != egui::Vec2::ZERO + || input.middle + || input.secondary_down + || (input.primary_nav.is_some() && input.primary_down) + || input.mode.is_some() + || app.viewport.axis_drag.is_some() + || app.viewport.spin + || app.cam_anim.is_some(); + let hits = input + .hover + .filter(|_| geometry_inside && !navigating && !waiting) + .map(|p| crate::viewport::pick_cached(app, &crate::viewport::projection(app, geometry_rect), p)) + .unwrap_or_default(); + let candidate = assign::candidate(app, &hits, input.mods); + app.viewport.hover = candidate.as_ref().map(|(hit, _)| hit.clone()); + // No target while blank or misaligned; still drain drag release / Escape. + let assigning = assign::input(app, ui, &response, candidate.as_ref(), geometry_inside && !navigating && !waiting); + if !waiting && !assigning && geometry_inside && !navigating { + assign::hover_tooltip(app, &response, candidate.as_ref()); + } + if !waiting && !assigning && response.clicked_by(egui::PointerButton::Primary) && geometry_inside && !navigating { + let (add, toggle) = crate::tool_modifiers::selection_click( + crate::tool_modifiers::Held::from_modifiers(input.mods), + app.preferences.selection_shift_add_only, + ); + crate::viewport::select(app, candidate.as_ref().map(|(_, sel)| sel.clone()), add, toggle); + } + if !waiting + && response.secondary_clicked() + && let Some((crate::viewport::Hit::Face { body, .. }, _)) = &candidate + { + if let Some(candidate) = &candidate { + assign::context(app, candidate); + } + crate::context_menu::open_for(app, input.hover.unwrap_or(rect.center()), crate::context_menu::Target::Body { name: body.clone() }); + } + } else { + app.viewport.hover = None; + } + let bg = app.render_workspace.view.draft.background; + ui.painter().rect_filled(viewport, 0.0, Color32::from_rgb(bg[0], bg[1], bg[2])); + // Reobserve after the existing shared navigation path, before any pixel paint. + interactive::before_paint(app, ui.ctx()); + if interactive::paint(app, ui, rect) || interactive::blocks_geometry_input(app) { + shot::overlay(app, ui, viewport); + crate::viewport::axis_view(app, ui, viewport); + crate::navigation_bar_view::show(app, ui, viewport); + return; + } + let result = (|| -> Result<(), String> { + let exposure = product_preview_exposure(app)?; + if app.viewport.gpu.is_none() { + return Err(crate::i18n::tr("render.error_gpu_preview").into()); + } + let ppp = ui.ctx().pixels_per_point(); + let setup = &app.render_workspace.view.draft; + if setup.environment_rotation != 0.0 || setup.environment_intensity != 1.0 { + return Err(crate::i18n::tr("render.preview_environment_fixed").into()); + } + // A 4K or 5K viewport is past the preview's pixel budget: draw it smaller and filter it + // up into the viewport rather than refusing the frame. + let full = ((rect.width() * ppp).max(1.0) as u64, (rect.height() * ppp).max(1.0) as u64); + let (width, height) = preview_size(app.session.render_viewport(), full); + let mut request = RenderRequest { + backend: Some(setup.backend.clone()), + mode: setup.mode, + operation: RenderOperation::Viewport, + width, + height, + format: None, + features: Vec::new(), + policy: Default::default(), + }; + solidcraft_engine::render::resolve_request(&[app.session.render_backend()], &request).map_err(|e| e.to_string())?; + if app.session.model.is_stale() { + return Err(crate::i18n::tr("render.error_finish_gesture").into()); + } + let mut visibility = std::collections::hash_map::DefaultHasher::new(); + app.session.visibility.hidden_bodies.hash(&mut visibility); + app.session.visibility.hidden_occurrences.hash(&mut visibility); + let budget = preferred_geometry_budget(app.render_workspace.geometry_budget, app.preferences.render_previous_geometry_budget); + let signature = + (app.session.revision, Arc::as_ptr(&app.session.world_state()) as usize, visibility.finish() ^ assign::preview_key(app), budget); + let preview = assign::preview(app); + let previous_key = app.render_workspace.key; + app.render_workspace.prepare_preview(signature, || { + let mut scene = solidcraft_engine::product_scene::extract(&app.session).map_err(|error| error.to_string())?; + assign::preview_scene(&mut scene, preview.as_ref())?; + Ok(scene) + })?; + if app.render_workspace.key != previous_key { + ui.ctx().request_repaint(); + } + let scene = app.render_workspace.scene.as_ref().ok_or(crate::i18n::tr("render.error_no_scene"))?; + if let Some(error) = app.render_workspace.upload_error.lock().ok().and_then(|e| e.clone()) { + return Err(upload_refusal(app.render_workspace.preview_upload_bytes.unwrap_or(0) as u64, &error)); + } + request.features = scene.required_features(); + solidcraft_engine::render::resolve_request(&[app.session.render_backend()], &request).map_err(|e| e.to_string())?; + let key = app.render_workspace.key.ok_or(crate::i18n::tr("render.error_no_geometry"))?; + if scene.bounds.is_empty() { + return Err(crate::i18n::tr("render.error_visible_solid").into()); + } + let camera = app.cam; + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye(); + let highlight_key = crate::viewport::highlight_key(app); + if highlight_key != app.viewport.hl_key { + let overlay = crate::viewport::build_highlight(app); + if let Ok(mut slot) = app.viewport.hl_slot.lock() { + *slot = Some(overlay); + } + app.viewport.hl_key = highlight_key; + } + let slot = app.render_workspace.slot.clone(); + let callback = ViewportCallback(Frame { + product_lights: Some(light::preview(app)?), + product_exposure_ev: exposure, + product: true, + upload_error: Some(app.render_workspace.upload_error.clone()), + key, + slot: slot.clone(), + sketch_key: 0, + sketch_slot: slot.clone(), + hl_key: app.viewport.hl_key, + hl_slot: app.viewport.hl_slot.clone(), + pv_key: 0, + pv_slot: slot, + pv_hide: false, + view_proj: camera.view_proj(f64::from(rect.width() / rect.height().max(1.0)), radius).to_f32(), + back: camera.back().to_f32(), + size_px: [rect.width() * ppp, rect.height() * ppp], + clip: [0.0; 4], + cap: [0.0; 4], + images: Vec::new(), + points: Vec::new(), + analysis: [0.0; 8], + analysis_colors: [0.0; 36], + access: None, + outline: false, + // Product rendering has its own lighting; AO is a Design viewport setting. + ao_radius: 0.0, + ao_samples: solidcraft_gpu::view::AO_SAMPLES, + eye: [eye.x as f32, eye.y as f32, eye.z as f32, if camera.fov > 0.0 { 1.0 } else { 0.0 }], + ssaa: if width < full.0 { width as f32 / full.0 as f32 } else { 1.0 }, + hover_tint: [f32::from(Tokens::get().hover_face_lift) / 255.0; 3], + selection_tint: { + let c = Tokens::get().body_selected; + [f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0] + }, + }); + ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback)); + Ok(()) + })(); + if let Err(error) = result { + preview_error(app, ui, rect, &error); + } + shot::overlay(app, ui, viewport); + crate::viewport::axis_view(app, ui, viewport); + crate::navigation_bar_view::show(app, ui, viewport); +} + +/// Apply validated UI requests after the same registry call used by automation. +pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Value) -> Result<(), String> { + match id { + "render.interactive" => { + let input: solidcraft_engine::schema::render_ui::InteractiveParams = + serde_json::from_value(reply.clone()).map_err(|error| error.to_string())?; + interactive::apply_command(app, input.action)?; + } + "render.preflight.copy" => { + app.render_workspace.clipboard_text = Some(reply["text"].as_str().ok_or("invalid check report")?.to_string()); + } + "render.output.size" => { + let width = reply["width"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output width")?; + let height = reply["height"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output height")?; + if cpu::image_limits(app).fit(u64::from(width), u64::from(height), None) != Some((u64::from(width), u64::from(height))) { + return Err(app.tr("render.output_over_budget").into()); + } + app.render_workspace.view.inspector.resolution.custom = reply["custom"].as_bool().unwrap_or(false); + app.render_workspace.view.draft.width = width; + app.render_workspace.view.draft.height = height; + app.render_workspace.view.dirty = true; + } + "render.result.view" | "render.result.close" => { + let view = reply["view"].as_str().ok_or("invalid result view")?; + if view == "actual" && reduced_display(app) { + return Err(app.tr("render.result_reduced_display").into()); + } + app.render_workspace.view.result = view != "model"; + match view { + "fit" => fit_result(app), + "actual" => app.render_workspace.view.result_scale = ResultScale::Actual, + _ => {} + } + app.cancel_view_animation(); + app.viewport.nav = None; + app.viewport.key_hold = None; + app.viewport.orbit_free = None; + } + "render.result.copy" => { + let job = serde_json::from_value(reply["frame"]["job"].clone()).map_err(|e| e.to_string())?; + let frame = app + .session + .render_job_handle(job) + .map_err(|e| e.to_string())? + .frame() + .map_err(|e| e.to_string())? + .ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; + let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, RenderLimits::default(), 4096)?; + app.render_workspace.clipboard_image = Some(image); + } + _ => {} + } + Ok(()) +} + +pub(crate) fn progress_pill(app: &mut SolveApp, ui: &mut egui::Ui) -> bool { + if !ribbon::busy(app) { + return false; + } + let Some(job) = app.render_workspace.view.job else { return false }; + let Ok(status) = app.session.execute("render.status", &json!({"job":job})) else { return false }; + let phase = status["progress"]["phase"].as_str().unwrap_or("unknown"); + if !matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling") { + return false; + } + let done = status["progress"]["done"].as_u64().unwrap_or(0); + let total = status["progress"]["total"].as_u64().unwrap_or(1).max(1); + let fraction = (done as f64 / total as f64).clamp(0.0, 1.0) as f32; + let phase_key = format!("render.image_{phase}"); + let name = app.render_workspace.view.job_shot.as_ref().unwrap_or(&app.render_workspace.view.name).clone(); + let cancel = + crate::ui_kit::progress_action(ui, &format!("{name} · {} · {:.0}%", app.tr(&phase_key), fraction * 100.0), fraction, app.tr_label("Cancel")); + crate::scenario::publish_target("render:progress-cancel", cancel.rect); + if cancel.clicked() { + app.start("render.cancel"); + } + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + true +} + +pub(crate) fn environment_overlay(app: &mut SolveApp, ui: &mut egui::Ui, viewport: egui::Rect) { + environment::ring_overlay(app, ui, viewport); +} + +pub(crate) fn interactive_command_info(app: &SolveApp, command: &solidcraft_engine::CommandSpec) -> solidcraft_engine::CommandInfo { + let mut info = ribbon::command_info(app, command); + // A drawing tool on the SKETCH tab kept shown outside a sketch starts one (#7904). + if crate::workspace::starts_a_sketch(app, command.id) { + info.enabled = true; + info.disabled_reason = None; + } + info +} +pub(crate) fn start_interactive(app: &mut SolveApp, id: &str) -> bool { + let handled = assign::start(app, id) || ribbon::start(app, id); + // Opening Appearance Advanced must still reach its atmosphere controls after leaving Wear. + if handled + && id == "render.aging.describe" + && app.render_workspace.view.inspector.page == inspector::Page::Appearance + && app.render_workspace.view.selection == RenderSelection::Wear + { + let _ = app.run("view.render_select", json!({"kind":"nothing"})); + // Clearing semantic focus routes to Scene; retain the explicit Advanced destination. + app.render_workspace.view.inspector.page = inspector::Page::Appearance; + } + handled +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs new file mode 100644 index 000000000..e9c836fc6 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_cpu.rs @@ -0,0 +1,870 @@ +//! 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::>(), + 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, ¬e, 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::>(), + 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::>(), + 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, + #[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, + /// Request-local, explicitly selected certified-box nesting; never inferred from GPU state. + pub nested_media: bool, + bindings: std::collections::BTreeMap, +} + +#[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, + // 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, +} + +#[derive(Clone, Debug)] +pub(super) struct Checked { + pub request: Value, + pub revision: u64, + pub environment: Value, + document: std::sync::Weak, +} + +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 { + 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) -> 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)?; + if !app.preferences.render_cpu_interactive_explicit_sampling { + let options = params + .get_mut("raytrace") + .and_then(Value::as_object_mut) + .ok_or_else(|| app.tr("render.error_provisional_identity").to_string())?; + // The original request was validated above. Only an explicit progressive + // object is replaced; Fixed stays Fixed until the engine's existing + // preview conversion applies primary/reflection1 and the fallback16/0. + if options.get("progressive").is_some_and(|value| !value.is_null()) { + options.insert("progressive".into(), json!(solidcraft_engine::render::job::CpuProgressiveOptions::default())); + } + } + Ok(()) +} + +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, 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> = 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); + } +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_tests.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_tests.rs new file mode 100644 index 000000000..9fe7d2c44 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_tests.rs @@ -0,0 +1,11763 @@ +use super::*; +use crate::scenario::Harness; +use solidcraft_engine::Session; + +fn environment_editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 1800.0))), events, ..Default::default() }, + |ui| { + ui.set_width(308.0); + environment::editor(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +fn environment_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"gpu_path","options":{"environment":{"kind":"sky"}}}}})).unwrap(); + setups::load(&mut h.app); + h +} + +#[test] +fn environment_editor_e4_variants_keep_all_five_sections_in_order() { + for variant in ["embedded", "sky", "file"] { + let mut h = environment_editor_fixture(); + if variant == "embedded" { + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + } else if variant == "file" { + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "C:/hdr/studio.hdr".into() }; + } else { + h.app.render_workspace.view.studio.backdrop_enabled = true; + } + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let mut previous = -1.0; + let source_row = crate::scenario::rect_of("dialog:control:Source").unwrap(); + let change = crate::scenario::rect_of("render:environment:change").unwrap(); + assert!(source_row.contains_rect(change), "{variant}: Change must fit beside Source"); + for key in [ + "render.env_source", + "render.environment.orientation", + "render.env_backdrop", + "render.environment.ground", + "render.environment.atmosphere", + ] { + let rect = crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap(); + assert!(rect.top() > previous, "{variant}: {key} out of order"); + previous = rect.top(); + } + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.replace", + "render.environment.fit", + "render.environment.floor_wall", + "render.environment.cyclorama", + "render.environment.medium", + "render.environment.phase", + ] { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}: {text}"); + } + for key in match variant { + "embedded" => &["render.environment.embedded", "render.environment.builtin"][..], + "file" => &["render.environment.choose", "render.environment.check"][..], + _ => &[ + "render.environment.zenith", + "render.environment.horizon", + "render.environment.sky_ground", + "render.environment.start", + "render.environment.end", + ][..], + } { + assert!(text.contains(h.app.tr(key)), "{variant}: missing {key}"); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "opening {variant} must never save"); + output.textures_delta.clear(); + } +} + +#[test] +fn environment_editor_unsupported_methods_keep_controls_and_reasons_without_switching() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = environment_editor_fixture(); + h.app.render_workspace.view.method = method; + let before = h.app.session.doc.clone(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + for key in [ + "render.environment.needs_gpu", + "render.environment.gradient_gpu", + "render.environment.blur_pending", + "render.environment.world_pending", + "render.environment.medium", + "render.environment.min", + "render.environment.max", + ] { + assert!(text.contains(h.app.tr(key)), "missing {key}: {text}"); + } + output.textures_delta.clear(); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_none()); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn environment_editor_gradient_and_atmosphere_refuse_hostile_values_atomically() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for value in [f64::NAN, f64::INFINITY, -1.0, 1e300] { + let mut gradient = h.app.render_workspace.view.studio.backdrop; + gradient.radius = value; + assert!(environment::commit_gradient(&mut h.app, true, gradient).is_err()); + h.app.render_workspace.view.studio.volume = + Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: value, ..Default::default() }); + assert!(setups::save(&mut h.app).is_err()); + h.app.render_workspace.view.studio.volume = None; + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + environment::commit_gradient(&mut h.app, true, Default::default()).unwrap(); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_editor_stage_removal_requires_confirm_and_rejects_stale_answers() { + for stale in [false, true] { + let mut h = environment_editor_fixture(); + environment::commit_ground(&mut h.app, true, environment::Ground { margin: 1.0, gap: 0.1, color: [0.18; 3] }).unwrap(); + let before = h.app.session.doc.clone(); + environment::request_stage_removal(&h.app, &h.ctx); + for _ in 0..3 { + environment_editor_frame(&mut h, vec![]); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(crate::scenario::rect_of("dialog:ok").is_some()); + if stale { + h.app.run("render.settings.set", json!({"name":"Other","set":{"width":42}})).unwrap(); + } + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("dialog:ok").unwrap().center(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert_eq!(h.app.session.undo.len(), undo + usize::from(!stale)); + assert_eq!(h.app.render_workspace.view.draft.stage.is_empty(), !stale); + } +} + +#[test] +fn environment_editor_checked_file_embeds_bytes_and_keeps_the_recheck_banner() { + let mut h = environment_editor_fixture(); + let path = h.dir.join("environment-editor.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + environment::persist(&mut h.app); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + assert!(matches!(h.app.render_workspace.view.studio.hdr, hdr::Input::FileCaptured { .. })); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(308.0, 3000.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.job.text.contains(h.app.tr("render.environment.checked")))); + output.textures_delta.clear(); + let before = h.app.session.doc.clone(); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + environment::persist(&mut h.app); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "changed bytes require rechecking"); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_medium_toggle_saves_one_command_without_a_gpu_host() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let at = crate::scenario::rect_of("render:volume-enable").unwrap().center(); + let undo = h.app.session.undo.len(); + for pressed in [true, false] { + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + assert!(h.app.render_workspace.view.studio.volume.is_some()); + assert_eq!(h.app.session.undo.len(), undo + 1); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(h.app.session.doc.render.setups[&h.app.render_workspace.view.name], expected); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.studio.volume.is_none()); +} + +#[test] +fn environment_ring_angles_snap_wrap_and_refuse_hostile_geometry() { + let center = egui::pos2(100.0, 200.0); + for (point, expected) in + [(egui::pos2(150.0, 200.0), 0.0), (egui::pos2(100.0, 250.0), 90.0), (egui::pos2(50.0, 200.0), 180.0), (egui::pos2(100.0, 150.0), -90.0)] + { + assert_eq!(environment::pointer_angle(point, center, 50.0), Some(expected)); + } + assert_eq!(environment::drag_rotation(170.0, 170.0, -170.0, false), Some(-170.0)); + assert_eq!(environment::drag_rotation(170.0, 0.0, 30.0, true), Some(-165.0)); + assert_eq!(environment::drag_rotation(-170.0, 0.0, -30.0, true), Some(165.0)); + assert_eq!(environment::drag_rotation(0.0, 0.0, 180.0, false), Some(-180.0)); + assert_eq!(environment::pointer_angle(center, center, 50.0), None); + for radius in [0.0, -1.0, f32::NAN, f32::INFINITY, 1e9] { + assert_eq!(environment::pointer_angle(egui::pos2(150.0, 200.0), center, radius), None); + } + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(environment::pointer_angle(egui::pos2(value, 200.0), center, 50.0), None); + assert_eq!(environment::pointer_angle(center, egui::pos2(100.0, value), 50.0), None); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300] { + assert_eq!(environment::drag_rotation(value, 0.0, 20.0, false), None); + assert_eq!(environment::drag_rotation(0.0, value, 20.0, true), None); + assert_eq!(environment::drag_rotation(0.0, 0.0, value, false), None); + } +} + +fn environment_ring_frame(h: &mut Harness, mods: egui::Modifiers, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + focused: true, + events: std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(), + ..Default::default() + }, + |ui| { + let viewport = ui.max_rect(); + show(&mut h.app, ui); + environment_overlay(&mut h.app, ui, viewport); + }, + ); + output.textures_delta.clear(); +} + +fn environment_ring_fixture() -> Harness { + let mut h = environment_editor_fixture(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.preferences.nav = crate::prefs::OPENSCAD_NAV.into(); + h.app.cam.fit(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap().bounds); + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + h +} + +#[test] +fn render_workspace_frame_rect_fits_centres_and_refuses_hostile_sizes() { + let viewport = egui::Rect::from_min_size(egui::pos2(100.0, 40.0), egui::vec2(800.0, 600.0)); + for aspect in [16.0 / 9.0, 1.5, 1.0, 0.8, 9.0 / 16.0, 0.01, 100.0] { + let frame = shot::frame_rect(aspect, viewport).unwrap(); + assert!(viewport.contains_rect(frame)); + assert_eq!(frame.center(), viewport.center()); + assert!((f64::from(frame.width() / frame.height()) - aspect).abs() < 0.001); + assert!(frame.width() == viewport.width() || frame.height() == viewport.height()); + } + for aspect in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::MAX, 1e-300] { + assert!(shot::frame_rect(aspect, viewport).is_none()); + } + for size in [egui::Vec2::ZERO, egui::vec2(0.0, 400.0), egui::vec2(f32::NAN, 10.0), egui::vec2(f32::MAX, f32::MAX), egui::vec2(-10.0, 20.0)] { + assert!(shot::frame_rect(1.5, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none()); + } +} + +fn frame_editor_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1200})); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"width":800,"height":600,"camera":h.app.cam}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h +} + +#[test] +fn environment_ring_drag_is_one_undo_snaps_and_never_navigates_the_camera() { + use egui::{Event, Modifiers, PointerButton}; + let mut h = environment_ring_fixture(); + environment::commit_environment(&mut h.app, json!({"rotation_deg":170})).unwrap(); + environment_ring_frame(&mut h, Modifiers::NONE, vec![]); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let at = |degrees: f32| ring.center + egui::vec2(degrees.to_radians().cos(), degrees.to_radians().sin()) * ring.radius; + let press = at(0.0); + let before = h.app.session.doc.clone(); + let camera = h.app.cam; + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + for pressed in [true, false] { + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }, + ], + ); + } + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "a Shift click without a drag does not snap or save"); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(press), + Event::PointerButton { pos: press, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + for angle in [10.0, 20.0, 30.0] { + environment_ring_frame(&mut h, Modifiers::SHIFT, vec![Event::PointerMoved(at(angle))]); + assert!(Arc::ptr_eq(&before, &h.app.session.doc), "drag is temporary"); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera, "OpenSCAD left-drag must not orbit through the ring"); + } + let end = at(30.0); + environment_ring_frame( + &mut h, + Modifiers::SHIFT, + vec![Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::SHIFT }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!((h.app.render_workspace.view.studio.rotation_rad.to_degrees() + 165.0).abs() < 1e-6); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert!(crate::scenario::rect_of("render:environment:ring-degrees").is_some()); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); +} + +#[test] +fn environment_ring_cancel_or_stale_revision_discards_the_drag() { + use egui::{Event, Modifiers, PointerButton}; + for stale in [false, true] { + let mut h = environment_ring_fixture(); + let ring = h.app.render_workspace.view.environment_ring.geometry.unwrap(); + let start = ring.center + egui::vec2(ring.radius, 0.0); + let end = ring.center + egui::vec2(0.0, ring.radius); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![ + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + ], + ); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(end)]); + if stale { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"width":640}})).unwrap(); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + let cancel = if stale { + vec![] + } else { + vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }] + }; + environment_ring_frame(&mut h, Modifiers::NONE, cancel); + environment_ring_frame(&mut h, Modifiers::NONE, vec![Event::PointerMoved(start)]); + environment_ring_frame( + &mut h, + Modifiers::NONE, + vec![Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], + ); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn environment_ring_visibility_follows_editor_target_and_live_canvas() { + let mut h = environment_ring_fixture(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.app.render_workspace.view.selection = RenderSelection::Environment; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_some()); + h.app.render_workspace.view.selection = RenderSelection::Nothing; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); + h.app.render_workspace.view.inspector.page = inspector::Page::Environment; + h.app.render_workspace.view.result = true; + environment_ring_frame(&mut h, egui::Modifiers::NONE, vec![]); + assert!(h.app.render_workspace.view.environment_ring.geometry.is_none()); +} + +#[test] +fn environment_editor_opening_pages_and_sources_preserves_design_and_history() { + let mut h = environment_editor_fixture(); + let before = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for page in [inspector::Page::Environment, inspector::Page::Background] { + h.app.render_workspace.view.inspector.page = page; + environment_editor_frame(&mut h, vec![]); + assert!(crate::scenario::rect_of("render:environment:rotation-slider").is_some()); + h.app.ui.show_browser = false; + environment::open_sources(&mut h.app); + assert!(h.app.ui.show_browser); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len())); + } +} + +#[test] +fn environment_editor_controls_commit_one_undo_each_and_refuse_hostile_edits() { + let mut h = environment_editor_fixture(); + for request in [json!({"rotation_deg":215}), json!({"intensity":2.5})] { + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc, before); + h.app.run("edit.redo", json!({})).unwrap(); + } + for (color, transparent) in [([40, 80, 120], false), ([40, 80, 120], true), ([40, 80, 120], false)] { + let undo = h.app.session.undo.len(); + environment::commit_backdrop(&mut h.app, color, transparent).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let mut ground = environment::Ground { margin: 0.25, gap: 0.1, color: [0.18; 3] }; + for edit in 0..5 { + match edit { + 1 => ground.margin = 1.0, + 2 => ground.gap = 0.25, + 3 => ground.color = [0.1, 0.3, 0.5], + _ => {} + } + let undo = h.app.session.undo.len(); + environment::commit_ground(&mut h.app, edit != 4, ground.clone()).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for request in [json!({"rotation_deg":1e300}), json!({"intensity":-1}), json!({"rotation_deg":"NaN"}), json!(null), json!([])] { + assert!(environment::commit_environment(&mut h.app, request).is_err()); + } + assert!(environment::commit_ground(&mut h.app, true, environment::Ground { gap: f64::NAN, ..ground }).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn environment_editor_slider_drag_commits_only_on_release() { + let mut h = environment_editor_fixture(); + environment_editor_frame(&mut h, vec![]); + let rect = crate::scenario::rect_of("render:environment:rotation-slider").unwrap(); + let start = rect.center(); + let end = egui::pos2(rect.right() - 20.0, start.y); + let undo = h.app.session.undo.len(); + environment_editor_frame( + &mut h, + vec![ + egui::Event::PointerMoved(start), + egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }, + ], + ); + environment_editor_frame(&mut h, vec![egui::Event::PointerMoved(end)]); + assert_eq!(h.app.session.undo.len(), undo, "dragging is temporary"); + environment_editor_frame( + &mut h, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }], + ); + assert_eq!(h.app.session.undo.len(), undo + 1, "release saves one edit"); + environment_editor_frame(&mut h, vec![]); + assert_eq!(h.app.session.undo.len(), undo + 1); +} + +#[test] +fn environment_editor_hdr_header_reads_catalog_without_applying_or_saving() { + let mut h = environment_editor_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(305.0, 1600.0))), ..Default::default() }, + |ui| environment::editor(&mut h.app, ui), + ); + let named = crate::test_support::text_shapes(&output).any(|text| text.galley.job.text.contains("Neutral side softbox")); + output.textures_delta.clear(); + assert!(named); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for request in [json!({"rotation_deg":540}), json!({"intensity":0})] { + let undo = h.app.session.undo.len(); + environment::commit_environment(&mut h.app, request).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + } +} + +#[test] +fn render_workspace_frame_opening_editor_and_presets_never_mutates_or_starts_a_job() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + h.frames(4); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(crate::scenario::rect_of("render:shot:name").is_some()); + assert!(crate::scenario::rect_of("render:frame:aspect:16:9").is_some()); + assert!(crate::scenario::rect_of("render:frame:overlay").is_some()); + assert_eq!(shot::selected(&h.app), Some("Hero")); + h.step(&json!({"click":{"handle":"render:frame:thirds"}})).unwrap(); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + let mut h = frame_editor_fixture(); + let camera = Camera { fov: 175f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.frames(4); + assert_eq!(h.app.cam, camera, "opening must preserve valid FOVs outside the slider's usual editing range"); +} + +#[test] +fn render_workspace_frame_guides_are_transient_and_overlay_visibility_is_contextual() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.run("view.render_frame", json!({"aspect":"16:9","thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + assert!(shot::overlay_visible(&h.app)); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0)); + let frame = shot::preview_rect(&h.app, viewport).unwrap(); + assert!((frame.width() / frame.height() - 16.0 / 9.0).abs() < 0.001); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + assert!(!shot::overlay_visible(&h.app)); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + assert!(shot::overlay_visible(&h.app)); + h.app.render_workspace.view.result = true; + assert!(!shot::overlay_visible(&h.app)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.doc.render.setups["Hero"].width, 800); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.render_workspace.view.frame.guides.thirds); + assert!(h.app.render_workspace.view.frame.guides.safe_area); + assert!(h.app.render_workspace.view.frame.guides.centre_mark); +} + +#[test] +fn render_workspace_frame_exposure_drag_is_one_saved_edit_and_undoes() { + let mut h = frame_editor_fixture(); + shot::edit_settings(&mut h.app, "Hero", json!({"job":{"method":"cpu_raytrace"}})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0, "exposure track: {track:?}"); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + assert_ne!( + h.app.session.doc.render.setups["Hero"].exposure_ev, 0.0, + "track: {track:?}; state: {:?}; status: {:?}", + h.app.render_workspace.view.frame, h.app.status + ); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +#[test] +fn render_workspace_scene_render_shot_captures_current_size_and_live_camera_without_saving() { + let mut h = frame_editor_fixture(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + shot::edit_settings(&mut h.app, "Hero", json!({"width":16,"height":12})).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let camera = Camera { distance: 85.0, fov: 35f64.to_radians(), ..h.app.cam }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + h.app.run("view.render_frame", json!({"thirds":true,"safe_area":true,"centre_mark":true})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Hero")); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16384).unwrap(); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().unwrap(); + assert_eq!((frame.info.width, frame.info.height), (16, 12)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_frame_aspect_click_edits_only_selected_shot_size_once_and_undoes() { + let mut h = frame_editor_fixture(); + h.frames(4); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:frame:aspect:16:9"}})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), (1920, 1080)); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + for (index, expected) in [(1, (1620, 1080)), (2, (1080, 1080)), (3, (864, 1080)), (4, (1080, 1920))] { + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", index).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert_eq!((saved.width, saved.height), expected); + assert_eq!(h.app.session.undo.len(), undo + 1); + } + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + shot::choose_aspect(&mut h.app, "Hero", 5).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert!(shot::choose_aspect(&mut h.app, "Hero", usize::MAX).is_err()); +} + +#[test] +fn render_workspace_frame_shot_edits_revert_duplicate_and_rename_use_existing_commands() { + let mut h = frame_editor_fixture(); + let before = h.app.session.doc.render.setups["Hero"].clone(); + let camera = Camera { distance: before.camera.distance * 2.0, ..before.camera }; + inspector::apply_camera_draft(&mut h.app, camera).unwrap(); + let undo = h.app.session.undo.len(); + assert!(shots::camera_modified(&h.app, "Hero")); + shot::edit_settings(&mut h.app, "Hero", json!({"camera":camera})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(!shots::camera_modified(&h.app, "Hero")); + h.app.run("edit.undo", json!({})).unwrap(); + shot::revert(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.cam, before.camera); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + shot::duplicate(&mut h.app, "Hero").unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + let copied = h.app.session.doc.render.setups.iter().find(|(name, _)| name.as_str() != "Hero").unwrap().1; + assert_eq!(copied, &h.app.session.doc.render.setups["Hero"]); + shot::rename(&mut h.app, "Hero", "Renamed").unwrap(); + assert_eq!(shot::selected(&h.app), Some("Renamed")); + assert_eq!(h.app.session.undo.len(), undo + 3); + let before = h.app.session.doc.to_json(); + for patch in [json!({"width":0}), json!({"width":u32::MAX}), json!({"height":1e300}), json!({"exposure_ev":33}), json!({"exposure_ev":null})] { + assert!(shot::edit_settings(&mut h.app, "Renamed", patch).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + } +} + +fn render_lights_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"cpu_raytrace","options":{"lights":[ + {"direction":[0.6,0,0.8],"color":[1,0.5,0.25],"intensity":3}, + {"direction":[-0.8,0,0.6],"color":[0.25,0.5,1],"intensity":2} + ]}}}}), + ) + .unwrap(); + enter(&mut h.app, true).unwrap(); + setups::load(&mut h.app); + h.app.pending_fit = None; + h +} + +#[test] +fn render_lights_solo_and_mute_filter_preview_and_render_copies_without_saving_or_history() { + let mut h = render_lights_fixture(); + let original = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let json = document.to_json(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + assert_eq!(light::preview(&h.app).unwrap().len(), 1); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["lights"][0]["intensity"], 0.0); + assert_eq!(request["settings"]["job"]["options"]["lights"][1]["intensity"], 2.0); + h.app.run("render.lights.mute", json!({"id":"directional:1","mute":true})).unwrap(); + assert!(light::preview(&h.app).unwrap().is_empty()); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["options"]["lights"][1]["intensity"], 0.0); + assert_eq!(setups::snapshot(&h.app).unwrap(), original); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.doc.to_json(), json); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + let visibility = h.app.render_workspace.view.lights.visibility.clone(); + assert!(h.app.run("render.lights.mute", json!({"id":"area:0","mute":true})).is_err()); + assert_eq!(h.app.render_workspace.view.lights.visibility, visibility); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.active()); +} + +#[test] +fn render_lights_editor_opening_and_disabled_gpu_types_never_edit_or_start_a_job() { + let mut h = render_lights_fixture(); + h.app + .run( + "render.settings.set", + json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{"area_lights":[ + {"center":[0,0,100],"u":[1000000,0,0],"v":[0,-1000000,0],"radiance":[0,0,0]} + ]}}}}}), + ) + .unwrap(); + setups::load(&mut h.app); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + h.step(&json!({"click":{"handle":"render:light:type:point"}})).unwrap(); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); + assert_eq!(light::rows(&h.app).unwrap()[0].geometry.kind(), "area"); +} + +#[test] +fn render_lights_edit_commands_refresh_selected_editor_and_keep_visibility_separate_from_undo() { + let mut h = render_lights_fixture(); + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + light::edit(&mut h.app, "render.lights.set", Some("directional:0"), Some(json!({"intensity_ev":2}))).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:0".into())); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 4.0); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, document); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + assert_eq!(light::rows(&h.app).unwrap()[0].intensity, 3.0); + light::edit(&mut h.app, "render.lights.duplicate", Some("directional:0"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("directional:2".into())); + light::edit(&mut h.app, "render.lights.remove", Some("directional:2"), None).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); +} + +#[test] +fn render_lights_fixed_studio_requests_carry_transient_weights_without_saving_them() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + h.app.run("render.lights.solo", json!({"id":"directional:1","solo":true})).unwrap(); + let raster = image_request(&h.app).unwrap(); + assert_eq!(raster["studio_weights"], json!([0.0, 1.0, 0.0])); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + assert_eq!(image_request(&h.app).unwrap()["studio_weights"], json!([0.0, 1.0, 0.0])); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + assert!(serde_json::to_value(setups::snapshot(&h.app).unwrap()).unwrap().get("studio_weights").is_none()); +} + +#[test] +fn render_lights_list_inspects_unsaved_ui_draft_without_applying_or_opening_anything() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = + Some(vec![solidcraft_engine::render::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 7.0 }]); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + let camera = h.app.cam; + let page = h.app.render_workspace.view.inspector.page; + let snapshot = setups::snapshot(&h.app).unwrap(); + let reply = h.app.run("render.lights.list", json!({"settings":snapshot})).unwrap(); + assert_eq!(reply["lights"].as_array().unwrap().len(), 1); + assert_eq!(reply["lights"][0]["id"], "directional:0"); + assert_eq!(reply["lights"][0]["name"], "Key"); + assert_eq!(reply["lights"][0]["intensity"], 7.0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, page); + assert_eq!(setups::snapshot(&h.app).unwrap(), snapshot); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +mod async_path_host { + + #[test] + fn cpu_and_raster_render_entries_keep_gpu_setup_unstarted_across_document_reset() { + use std::sync::atomic::{AtomicUsize, Ordering}; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + h.app.render_workspace.defer_path_host("not requested".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("a CPU/Raster method must not call this GPU factory".into()) + }); + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + enter(&mut h.app, true).unwrap(); + for _ in 0..3 { + sync_backend(&mut h.app); + } + // The synchronous state and retained factory prove that no worker was + // launched, even if a wrongly launched thread had not been scheduled yet. + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + + crate::documents::adopt(&mut h.app, Session::default()); + select_image_method(&mut h.app, method); + enter(&mut h.app, true).unwrap(); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("not requested")); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + } + + #[test] + fn explicit_gpu_selection_starts_once_and_keeps_its_receiver_across_document_changes() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut h = Harness::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let (started, seen) = mpsc::channel(); + let (release, wait) = mpsc::channel(); + h.app.render_workspace.defer_path_host("explicit request".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + started.send(()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + Err("deliberate device-free refusal".into()) + }); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + seen.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + + // A real in-progress factory is not abandoned or duplicated when a new + // document defaults back to Raster, or the user changes methods meanwhile. + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + let duplicate_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not duplicate".into(), move || { + duplicate_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected duplicate preparation".into()) + }); + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + select_image_method(&mut h.app, method); + sync_backend(&mut h.app); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + release.send(()).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("expected deliberate refusal") }; + assert_eq!(error, "deliberate device-free refusal"); + + // A method change or new document does not become an automatic retry. + crate::documents::adopt(&mut h.app, Session::default()); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("document reset lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("GPU selection lost the original failure") }; + assert_eq!(error, "deliberate device-free refusal"); + let retry_calls = calls.clone(); + h.app.render_workspace.defer_path_host("must not retry".into(), move || { + retry_calls.fetch_add(1, Ordering::SeqCst); + Err("unexpected replacement after terminal failure".into()) + }); + sync_backend(&mut h.app); + let PathHost::Failed(error) = &h.app.render_workspace.path_host else { panic!("terminal failure was replaced") }; + assert_eq!(error, "deliberate device-free refusal"); + assert!(h.app.render_workspace.pending_setup.is_none()); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + use super::*; + use solidcraft_engine::render::job; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + /// Advertise the path capability without opening a device or rendering anything. + struct TestExecutor; + impl job::ImageExecutor for TestExecutor { + fn descriptor(&self) -> job::Result { + let mut descriptor = job::CpuHost::cooperative().descriptor()?; + descriptor.id = ExecutorId::new("test-path").unwrap(); + descriptor.profiles[0].features.push(solidcraft_engine::render::RenderFeature::Progressive); + Ok(descriptor) + } + fn admit(&self, _: &ProductScene, _: &job::ImageRequest, _: job::JobOptions) -> job::Result { + panic!("setup tests must not render") + } + fn begin(&self, _: ProductScene, _: job::ImageRequest, _: job::JobOptions, _: job::CancelToken) -> job::Result> { + panic!("setup tests must not render") + } + } + + fn panel_fixture() -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h + } + + fn finish_setup(h: &mut Harness) { + let deadline = Instant::now() + Duration::from_secs(10); + while matches!(h.app.render_workspace.path_host, PathHost::Preparing(..)) { + assert!(Instant::now() < deadline, "test setup worker did not finish"); + h.frames(1); + std::thread::sleep(Duration::from_millis(1)); + } + h.frames(3); + } + + #[test] + fn design_frames_and_document_reset_never_start_the_deferred_path_host() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(5); + crate::documents::adopt(&mut h.app, Session::default()); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + enter(&mut h.app, true).unwrap(); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + assert!(h.app.render_workspace.pending_setup.is_some()); + assert_eq!(calls.load(Ordering::SeqCst), 0); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn first_render_before_adapter_install_starts_once_when_the_adapter_arrives() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = Arc::new(AtomicUsize::new(0)); + let observed = calls.clone(); + let mut h = panel_fixture(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + sync_backend(&mut h.app); + assert!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted)); + h.app.render_workspace.defer_path_host("late selected viewport".into(), move || { + observed.fetch_add(1, Ordering::SeqCst); + Err("deliberate device refusal".into()) + }); + sync_backend(&mut h.app); + finish_setup(&mut h); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + h.app.render_workspace.defer_path_host("must not retry".into(), || panic!("failed setup retried")); + enter(&mut h.app, false).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(5); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn a_fallback_viewport_replaces_an_unstarted_factory_without_opening_the_old_device() { + let mut h = Harness::new(); + h.app.render_workspace.defer_path_host("old hardware adapter".into(), || panic!("superseded device opened")); + h.app.render_workspace.defer_path_host("selected safe-mode adapter".into(), || Err("selected adapter unavailable".into())); + h.frames(5); + assert_eq!(h.app.render_workspace.setup_key.as_deref(), Some("selected safe-mode adapter")); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + enter(&mut h.app, true).unwrap(); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("expected selected adapter result") }; + assert_eq!(message, "selected adapter unavailable"); + } + + #[test] + fn preparing_keeps_frames_responsive_then_registers_ready_host() { + let mut h = panel_fixture(); + let cpu_host = h.app.session.render_job_host().unwrap().clone(); + let (release, wait) = mpsc::channel(); + let (started, thread) = mpsc::channel(); + h.app.render_workspace.path_host.start(move || { + started.send(std::thread::current().id()).unwrap(); + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + assert_ne!(thread.recv_timeout(Duration::from_secs(10)).unwrap(), std::thread::current().id()); + // A second viewport installation cannot replace or duplicate setup. + h.app.render_workspace.path_host.start(|| panic!("setup started twice")); + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(!h.app.session.render_backend().executors.iter().any(|e| e.id.as_str() == "test-path")); + let transparent = h.app.tr("render.image_transparent").to_string(); + h.step(&json!({"widget":transparent})).unwrap(); + assert!(h.app.render_workspace.view.transparent); + // Replacing the current document must retain the receiver while setup waits. + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Preparing(..))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + enter(&mut h.app, false).unwrap(); + release.send(()).unwrap(); + finish_setup(&mut h); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_ok()); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + assert!(h.app.session.render_job_host().unwrap().same_host(&cpu_host)); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + crate::documents::adopt(&mut h.app, Session::default()); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Ready(_))); + assert_eq!(h.app.session.render_backend().executors.iter().filter(|e| e.id.as_str() == "test-path").count(), 1); + } + + /// The first setup on an adapter shows a spinner, the time so far and a note; a later one + /// a bar estimated from the time the first took, which the preferences keep. + #[test] + fn setup_progress_is_estimated_from_the_last_setup_on_the_adapter() { + let mut h = panel_fixture(); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + let first = h.app.tr("render.gpu_path_first_setup").to_string(); + assert!(h.widget("GPU path tracer: compiling shaders…").is_some()); + assert!(h.widget(&first).is_some(), "the first setup explains the wait"); + assert!(h.widget("0:00").is_some(), "and counts the time"); + release.send(()).unwrap(); + finish_setup(&mut h); + let took = h.app.render_workspace.setup_seconds.get("Test GPU | Vulkan | 1.0").copied(); + assert!(took.is_some_and(|s| (0.0..10.0).contains(&s)), "{took:?}"); + + // The next start on the same adapter has an estimate, kept in the preferences. + let mut h = panel_fixture(); + h.app.load_prefs(&json!({"gpu_path_setup_seconds": {"Test GPU | Vulkan | 1.0": 120.0}}).to_string()); + h.app.render_workspace.setup_key = Some("Test GPU | Vulkan | 1.0".into()); + let (release, wait) = mpsc::channel::<()>(); + h.app.render_workspace.path_host.start(move || { + wait.recv_timeout(Duration::from_secs(10)).unwrap(); + job::ImageHost::with_executor(Arc::new(TestExecutor)).map_err(|e| e.to_string()) + }); + h.frames(3); + assert!(h.widget(&first).is_none()); + assert!(h.widget("0:00 / ~2:00").is_some(), "a bar with the estimate"); + release.send(()).unwrap(); + finish_setup(&mut h); + let prefs: serde_json::Value = serde_json::from_str(&h.app.prefs()).unwrap(); + assert!(prefs["gpu_path_setup_seconds"]["Test GPU | Vulkan | 1.0"].as_f64().is_some_and(|s| s < 10.0)); + } + + #[test] + fn hostile_setup_times_are_ignored() { + let times = load_setup_seconds(&json!({"a": -1.0, "b": 1e300, "c": "slow", "d": 30.0})); + assert_eq!(times.into_iter().collect::>(), [("d".to_string(), 30.0)]); + let many: serde_json::Map = (0..100).map(|i| (format!("gpu {i}"), json!(1.0))).collect(); + assert_eq!(load_setup_seconds(&serde_json::Value::Object(many)).len(), MAX_SETUP_TIMES); + } + + #[test] + fn setup_error_is_visible_and_survives_document_reset() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| Err("test driver refused the device".into())); + finish_setup(&mut h); + let message = "GPU path tracer unavailable: test driver refused the device"; + assert!(h.widget(message).is_some()); + assert!(h.widget("GPU path tracer: compiling shaders…").is_none()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + assert!(h.app.session.render_job_host().is_some()); + completed_preview(&mut h, [200, 210, 220]); + crate::documents::adopt(&mut h.app, Session::default()); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + assert!(h.widget(message).is_some()); + h.app.render_workspace.path_host.start(|| panic!("failed setup retried on viewport install")); + assert!(matches!(h.app.render_workspace.path_host, PathHost::Failed(_))); + } + + #[test] + fn disconnected_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + let (tx, rx) = mpsc::channel(); + h.app.render_workspace.path_host = PathHost::Preparing(rx, Instant::now()); + drop(tx); + h.frames(3); + assert!(h.widget("GPU path tracer unavailable: setup worker stopped without returning a host").is_some()); + } + + #[test] + fn panicking_setup_is_reported_in_the_panel() { + let mut h = panel_fixture(); + h.app.render_workspace.path_host.start(|| panic!("simulated driver panic")); + finish_setup(&mut h); + assert!(h.widget("GPU path tracer unavailable: GPU path tracer setup panicked").is_some()); + } + + #[test] + fn registration_failure_is_reported_in_the_panel() { + let mut h = panel_fixture(); + // A different host with the same CPU descriptor cannot be registered twice. + h.app.render_workspace.path_host.start(|| Ok(job::CpuHost::cooperative())); + finish_setup(&mut h); + let PathHost::Failed(message) = &h.app.render_workspace.path_host else { panic!("duplicate executor must fail") }; + assert!(h.widget(&format!("GPU path tracer unavailable: {message}")).is_some()); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opaque_pbr_product_gpu_and_cpu_share_color_and_material_semantics() { + use solidcraft_engine::render::{ + StandardView, + job::{CancelToken, ImageRequest, ImageTask, TaskPoll}, + }; + let mut s = Session::default(); + s.execute("solid.sphere", &json!({"radius":10,"body_name":"Original sphere"})).unwrap(); + const SIZE: u32 = 256; + let mut previous = None; + for (metallic, roughness) in [(0.0, 0.2), (0.0, 0.65), (1.0, 0.2), (1.0, 0.65)] { + s.execute( + "appearance.assign", + &json!({"bodies":["Original sphere"],"color":"#b47846", + "pbr":{"metallic":metallic,"roughness":roughness,"dielectric_ior":1.5}}), + ) + .unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(!gpu.pbr.is_empty() && gpu.tris.is_empty()); + assert_ne!(previous, Some(key)); + previous = Some(key); + let mut camera = Camera { fov: 0.0, ..Default::default() }; + camera.set_view(StandardView::Iso); + camera.fit(&scene.bounds); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let mut task = ImageTask::new( + scene, + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera, + width: SIZE, + height: SIZE, + background: [255; 3], + transparent_background: false, + integrator: Default::default(), + raytrace: None, + }, + CancelToken::default(), + ) + .unwrap(); + let mut png = None; + for _ in 0..100_000 { + if let TaskPoll::Complete(bytes) = task.step(4096).unwrap() { + png = Some(bytes); + break; + } + } + let cpu = image::load_from_memory(&png.expect("bounded original fixture completes")).unwrap().to_rgba8(); + assert_eq!(cpu.dimensions(), (SIZE, SIZE)); + let cpu = cpu.into_raw(); + for srgb in [false, true] { + let Some(gpu) = crate::gpu::render_product_offscreen( + gpu.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 0.0], + SIZE, + srgb, + ) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let at = |pixels: &[u8], x: usize, y: usize| { + let i = (y * SIZE as usize + x) * 4; + [pixels[i], pixels[i + 1], pixels[i + 2]] + }; + let mut core = 0usize; + let mut error = 0usize; + let mut outliers = 0usize; + for y in 2..SIZE as usize - 2 { + for x in 2..SIZE as usize - 2 { + // Exclude antialiased silhouettes: CPU uses 2x supersampling, GPU uses 1x. + if (y - 1..=y + 1).any(|ny| (x - 1..=x + 1).any(|nx| at(&cpu, nx, ny) == [255; 3] || at(&gpu, nx, ny) == [255; 3])) { + continue; + } + let delta = at(&cpu, x, y).into_iter().zip(at(&gpu, x, y)).map(|(a, b)| usize::from(a.abs_diff(b))).collect::>(); + error += delta.iter().sum::(); + outliers += usize::from(delta.iter().any(|d| *d > 12)); + core += 1; + } + } + assert!(core > 1000); + let mean = error as f64 / (3 * core) as f64; + eprintln!("PBR m={metallic} r={roughness} srgb={srgb}: core={core}, mean={mean}, outliers={outliers}"); + assert!(mean < 2.0 && outliers * 100 < core * 2, "CPU/GPU color or material interpretation differs"); + } + } +} + +#[test] +fn control_render_export_respects_upstream_file_scope() { + let mut h = Harness::new(); + let root = h.dir.join("allowed"); + let outside = h.dir.join("outside"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let roots = json!([root.to_string_lossy()]); + let response = h.call("ui.workspace", json!({"workspace":"render","allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let response = h.call("engine.execute", json!({"command":"render.start","params":{"settings":{"width":16,"height":16}},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + let job = response["result"]["job"].clone(); + for _ in 0..50 { + h.frames(1); + } + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); + for path in [outside.join("denied.png"), root.join("../outside/traversal.png")] { + for overwrite in [false, true] { + let response = h.call( + "engine.execute", + json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":overwrite},"allow_paths":roots}), + ); + assert_eq!(response["ok"], false, "{response}"); + assert!(response.to_string().contains("outside the folders this agent may use"), "{response}"); + } + } + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0); + let path = root.join("allowed.png"); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert!(path.is_file()); + let original = std::fs::read(&path).unwrap(); + let response = h.call("engine.execute", json!({"command":"render.export","params":{"job":job,"path":path,"overwrite":true},"allow_paths":roots})); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(std::fs::read(&path).unwrap(), original); +} + +#[test] +fn adopting_into_blank_document_resets_render_draft_and_preserves_hosts() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.render_workspace.view.name = "Old draft".into(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let mut incoming = Session::default(); + incoming.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + crate::documents::adopt(&mut h.app, incoming); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + assert!(h.app.session.render_job_host().is_some()); + assert_eq!(h.app.session.model.state().bodies.len(), 1); +} + +#[test] +fn clicked_image_controls_complete_cancel_and_export_without_dirtying_the_design() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.frames(1); + let check = h.app.tr("cmd.render_preflight").to_string(); + let start = h.app.tr("render.image_start").to_string(); + let export = h.app.tr("render.image_export").to_string(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":check})).unwrap(); + h.step(&json!({"widget":start})).unwrap(); + for _ in 0..50 { + h.frames(1); + if h.app.render_workspace.view.completed.is_some() { + break; + } + } + let good = h.app.render_workspace.view.completed.unwrap(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 768; + h.step(&json!({"widget":start})).unwrap(); + assert!(job_ready(&h.app, "render.cancel").is_ok()); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(5); + assert_eq!(h.app.render_workspace.view.completed, Some(good)); + assert_eq!( + h.app.session.execute("render.status", &json!({"job":h.app.render_workspace.view.job})).unwrap()["progress"]["phase"], + "cancelled" + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn saved_camera_survives_frames_and_product_fit_ignores_selection() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Product"})).unwrap(); + h.app.run("solid.box", json!({"corner":[100,0,0],"length":10,"width":20,"height":5,"body_name":"Other"})).unwrap(); + let camera = Camera { up: solidcraft_engine::render::UpAxis::Y, roll: 0.2, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"camera":camera,"background":[21,43,65]}})).unwrap(); + h.frames(3); + let design = h.app.cam; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + h.step(&json!({"widget":"Restore Saved Camera"})).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.background, [21, 43, 65]); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Product".into() }]; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + let selected_fit = h.app.cam; + assert_product_fits_canvas(&h.app); + h.app.session.selection.clear(); + h.app.cam = camera; + h.call("engine.execute", json!({"command":"view.fit","params":{}})); + h.frames(3); + assert_eq!(h.app.cam, selected_fit, "Fit Product ignores the selected subset"); + enter(&mut h.app, false).unwrap(); + assert_eq!(h.app.cam, design); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn progressive_image_controls_route_to_the_registered_host() { + let host = solidcraft_gpu::select::Policy::from_env() + .and_then(|policy| solidcraft_gpu::select::pick(policy).ok_or_else(|| "no qualifying adapter".to_string())) + .and_then(|(adapter, _)| solidcraft_gpu::path::host_on_adapter(&adapter).map_err(|e| e.to_string())); + let host = match host { + Ok(host) => host, + Err(e) => { + let expected = !solidcraft_gpu::select::path_backends().is_empty(); + assert!(!expected || std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GPU unavailable: {e}"); + eprintln!("skipping progressive UI device test: {e}"); + return; + } + }; + let mut h = Harness::new(); + h.app.render_workspace.path_host = PathHost::Ready(host); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.call("ui.resize", json!({"width":1600,"height":1600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.samples = 4; + h.app.render_workspace.view.max_depth = 3; + h.app.render_workspace.view.seed = 7; + h.app.render_workspace.view.draft.exposure_ev = 0.5; + h.app.render_workspace.view.studio.tone_map = solidcraft_engine::render::job::ToneMap::AcesFitted; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.studio.lens.aperture_radius_mm = 0.0; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.ambient = [0.75; 3]; + // The UI request reaches the real registered host with a coat and captured map. + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut material = materials::Binding::new(target, &h.app); + material.coat_enabled = true; + material.maps_enabled = true; + let map_path = h.dir.join("original-color.png"); + image::RgbaImage::from_pixel(1, 1, image::Rgba([80, 160, 220, 255])).save(&map_path).unwrap(); + material.maps.color = map_path.to_string_lossy().into_owned(); + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(material); + h.frames(3); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + let checked = image_params(&h.app).unwrap(); + assert_eq!(checked["raytrace"]["clear_coats"][0]["weight"], 1.0); + assert_eq!(checked["raytrace"]["textures"][0]["base_color_srgb"], map_path.to_string_lossy().as_ref()); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while h.app.render_workspace.view.completed.is_none() { + assert!(std::time::Instant::now() < deadline, "progressive UI job did not complete"); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.frames(1); + } + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["frame"]["executor"], "gpu-path", "{status}"); + assert_eq!(status["options"]["samples"], 4); + assert_eq!(status["options"]["max_depth"], 3); + assert_eq!(status["options"]["seed"], 7); + assert_eq!(status["options"]["exposure_ev"], 0.5); + assert_eq!(status["options"]["tone_map"], "aces_fitted"); + assert_eq!(status["options"]["lens"]["aperture_radius_mm"], 0.0); + assert_eq!(status["options"]["lighting"]["environment"], json!([0.75, 0.75, 0.75])); + assert_eq!(status["textures"]["bodies"], 1); + let export = h.app.tr("render.image_export").to_string(); + h.step(&json!({"widget":export})).unwrap(); + assert!(h.dir.join("render.png").is_file()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + // A pack glass recipe follows the same production request and passes actual + // closed-mesh preparation. It never calls scalar appearance assignment. + let material = &mut h.app.render_workspace.view.materials.bindings[0]; + material.coat_enabled = false; + material.maps_enabled = false; + material.glass_enabled = true; + material.glass = materials::Glass::recipe("starter.glass.clear-soda-lime").unwrap(); + let checked = image_params(&h.app).unwrap(); + h.app.run("render.preflight", checked.clone()).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), checked); + let started = h.app.run("render.start", checked).unwrap(); + let job = serde_json::from_value(started["job"].clone()).unwrap(); + let status = h.app.session.render_job_handle(job).unwrap().wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, solidcraft_engine::render::job::Phase::Completed, "{:?}", status.error); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_render_workspace_saves_one_setup_and_restores_design_view() { + for language in ["en", "de", "ko", "ru"] { + let mut h = Harness::new(); + h.app.preferences.language = language.into(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + h.frames(3); + let camera = h.app.cam; + let flags = (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective); + let undo = h.app.session.undo.len(); + let at = crate::scenario::rect_of("workspace_switcher").unwrap().center(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + h.step(&json!({"click":{"handle":"menu:ui.workspace.render"}})).unwrap(); + assert!(active(&h.app)); + let heading = h.app.tr("render.page_scene").to_string(); + let perspective = h.app.tr("render.perspective").to_string(); + let save = h.app.tr("render.save_setup").to_string(); + let back = h.app.tr("render.return_design").to_string(); + assert!(h.widget(&heading).is_some(), "{language}"); + h.step(&json!({"click":{"handle":"render:scene:frame"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Camera); + h.step(&json!({"widget":perspective})).unwrap(); + assert!(!h.app.session.is_dirty(), "preview edits are staged"); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["Studio"].camera, h.app.cam); + h.step(&json!({"widget":back})).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.cam, camera); + assert_eq!(flags, (h.app.ui.show_grid, h.app.origin_shown(), h.app.ui.visual_style, h.app.ui.perspective)); + h.app.run("edit.undo", json!({})).unwrap(); + assert!(!h.app.session.is_dirty()); + } +} + +#[test] +fn render_drafts_and_capabilities_are_isolated_across_document_switches() { + let mut h = Harness::new(); + h.app.render_workspace.host = Some(host_executor(2048, true, 4).unwrap()); + sync_backend(&mut h.app); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.render_workspace.view.name = "First draft".into(); + h.app.render_workspace.view.draft.background = [20, 40, 60]; + h.app.render_workspace.view.dirty = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(!active(&h.app)); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.name, "First draft"); + assert_eq!(h.app.render_workspace.view.draft.background, [20, 40, 60]); + assert!(h.app.render_workspace.view.dirty); + assert_eq!(h.app.session.render_backend().executors.len(), 3); + h.app.run("file.new", json!({})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(h.app.session.render_backend().executors.len(), 3); +} + +#[test] +fn product_gpu_buffers_preserve_opacity_and_never_contain_overlays() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + let (key, gpu) = gpu_scene(&scene).unwrap(); + assert!(gpu.tris.is_empty()); + assert!(!gpu.glass.is_empty()); + let color = |v: &[u8]| { + let i = v.get(crate::gpu::TRI_SIZE - 4..).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; + gpu.palette.get(crate::gpu::PaletteIndex(i)) + }; + assert!(gpu.glass.as_chunks::<{ crate::gpu::TRI_SIZE }>().0.iter().all(|v| color(v) == Some([51, 102, 153, 102]))); + assert!(gpu.lines.is_empty() && gpu.overlay.is_empty() && gpu.under.is_empty() && gpu.hidden.is_empty() && gpu.ghost.is_empty()); + s.selection = vec![solidcraft_engine::Sel::Body { name: "Glass".into() }]; + s.section = Some((solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::X)); + let after = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(gpu_scene(&after).unwrap().0, key); + s.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.0})).unwrap(); + let invisible = solidcraft_engine::product_scene::extract(&s).unwrap(); + assert_eq!(invisible.meshes[0].opacity, 0.0); + let (_, empty) = gpu_scene(&invisible).unwrap(); + assert!(empty.tris.is_empty() && empty.glass.is_empty()); +} + +#[test] +fn transmission_uses_legacy_preview_buffers_and_invalidates_the_opaque_cache() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":10,"width":10,"height":10,"body_name":"Glass"})).unwrap(); + let appearance = json!({"bodies":["Glass"],"color":"#336699", + "pbr":{"metallic":0,"roughness":0.1,"dielectric_ior":1.5}}); + s.execute("appearance.assign", &appearance).unwrap(); + let (opaque_key, opaque) = gpu_scene(&solidcraft_engine::product_scene::extract(&s).unwrap()).unwrap(); + assert!(!opaque.pbr.is_empty()); + let mut scene = solidcraft_engine::product_scene::extract(&s).unwrap(); + scene.meshes[0].transmission = + Some(solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::ZERO, None).unwrap()); + let (glass_key, glass) = gpu_scene(&scene).unwrap(); + assert_ne!(opaque_key, glass_key); + assert!(glass.pbr.is_empty()); + assert!(!glass.tris.is_empty()); + scene.meshes[0].opacity = 0.4; + let (_, transparent) = gpu_scene(&scene).unwrap(); + assert!(transparent.pbr.is_empty()); + assert!(!transparent.glass.is_empty()); +} + +#[test] +fn host_profiles_advertise_only_installed_opaque_pbr_not_hdri_refraction_or_final() { + use solidcraft_engine::render::*; + let host = host_executor(512, true, 4).unwrap(); + assert_eq!(host.limits.max_dimension, 512); + assert_eq!(host.profiles.len(), 1); + assert_eq!(host.profiles[0].features, vec![RenderFeature::Pbr]); + assert!(host.profiles[0].formats.is_empty()); + let mut s = Session::default(); + s.set_render_viewport(Some(host)).unwrap(); + let mut request = RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width: 512, + height: 512, + format: None, + features: Vec::new(), + policy: Default::default(), + }; + assert_eq!(resolve_request(&[s.render_backend()], &request).unwrap().executor.as_str(), "gpu-viewport"); + request.features = vec![RenderFeature::Pbr]; + assert!(resolve_request(&[s.render_backend()], &request).is_ok()); + for unsupported in [RenderFeature::Hdri, RenderFeature::Refraction, RenderFeature::Progressive] { + request.features = vec![unsupported]; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + } + request.features.clear(); + request.width = 513; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + request.width = 512; + request.mode = RenderMode::Final; + assert!(resolve_request(&[s.render_backend()], &request).is_err()); + assert!(host_executor(1024, false, 1).unwrap().availability != Availability::Available); + assert!(host_executor(1024, true, 0).is_err()); +} + +fn completed_preview(h: &mut Harness, background: [u8; 3]) -> solidcraft_engine::render::job::JobId { + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":16,"height":16,"background":background}})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + host.pump(16384).unwrap(); + if h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("small cooperative image did not complete within the work budget"); +} + +fn image_panel_frame(app: &mut SolveApp, ctx: &egui::Context) -> egui::FullOutput { + ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(285.0, 1200.0))), ..Default::default() }, + |ui| image_controls(app, ui), + ) +} + +#[test] +fn completed_image_is_painted_once_available_and_upload_is_cached() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none()); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + let texture = texture.as_ref().unwrap(); + let id = texture.id(); + assert_eq!(*cached_job, job); + assert_eq!(texture.size(), [16, 16]); + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert!(pixels.pixels.iter().all(|p| *p == Color32::from_rgb(20, 40, 60))); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!( + ctx.tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| { matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty()) }) + ); + let mut output = image_panel_frame(&mut h.app, &ctx); + assert!(!output.textures_delta.set.contains_key(&id), "repaint must reuse the texture"); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let path = h.dir.join("displayed.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png(), "displaying the image must not change export bytes"); +} + +#[test] +fn completed_image_keeps_last_export_during_work_and_updates_for_the_next_job() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&ctx); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(first); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + let old_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, first); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + let mut output = image_panel_frame(&mut h.app, &ctx); + let (cached_job, texture) = h.app.render_workspace.image.as_ref().unwrap(); + assert_eq!(*cached_job, second); + assert_ne!(texture.as_ref().unwrap().id(), old_texture); + assert!(output.textures_delta.free.contains(&old_texture)); + // egui requires frame texture deltas to be applied or cleared. + output.textures_delta.clear(); + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 42.0; + let framing = h.app.render_workspace.view.result_camera; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert!(h.app.render_workspace.image.is_none(), "another document must not show this image"); + assert!(!h.app.render_workspace.view.result); + crate::documents::switch(&mut h.app, 0); + image_panel_frame(&mut h.app, &ctx).textures_delta.clear(); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().0, second); + assert!(h.app.render_workspace.view.result); + assert_eq!(h.app.render_workspace.view.result_camera, framing); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + reset_document(&mut h.app); + assert!(h.app.render_workspace.image.is_none()); + assert!(!h.app.render_workspace.view.result); +} + +#[test] +fn completed_image_decoder_preserves_alpha_and_rejects_invalid_sizes_and_pngs() { + let mut png = std::io::Cursor::new(Vec::new()); + let pixels = image::RgbaImage::from_pixel(2, 1, image::Rgba([80, 120, 160, 128])); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + let decoded = decode_image(png.get_ref(), 2, 1).unwrap(); + assert_eq!(decoded.size, [2, 1]); + assert_eq!(decoded.pixels, vec![Color32::from_rgba_unmultiplied(80, 120, 160, 128); 2]); + for (width, height) in [(0, 1), (u32::MAX, 1), (4096, 4096), (1, 1), (3, 1)] { + assert!(decode_image(png.get_ref(), width, height).is_err(), "{width}x{height}"); + } + assert!(decode_image(b"invalid PNG", 2, 1).is_err()); +} + +#[test] +fn cpu_checkpoints_replace_only_the_provisional_texture_and_keep_final_export_and_framing() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(first); + h.app.render_workspace.view.job = Some(first); + cache_render_images(&mut h.app, &ctx); + let final_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let second = completed_preview(&mut h, [80, 100, 120]); + let frame = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.job = Some(second); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + assert_eq!(displayed_image(&h.app).unwrap().info.job, second); + assert!(displayed_image(&h.app).unwrap().preview.is_some()); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.distance = 123.0; + h.app.render_workspace.view.result_camera.target.x = 5.0; + let camera = h.app.render_workspace.view.result_camera; + let first_checkpoint = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + // Repeated or older metadata never re-decodes bytes, even if passed bad data. + cache_preview_frame(&mut h.app, &ctx, &info, b"must not decode again"); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), first_checkpoint); + info.frame_sequence = 2; + info.samples_per_pixel = 2; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + let newer = h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(); + assert_ne!(newer, first_checkpoint); + info.frame_sequence = 1; + cache_preview_frame(&mut h.app, &ctx, &info, b"out of order"); + remember_displayed_job(&mut h.app, false); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().info.frame_sequence, 2); + assert_eq!(h.app.render_workspace.preview_image.as_ref().unwrap().image.as_ref().unwrap().id(), newer); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), final_texture); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + let path = h.dir.join("checkpoint-export-is-final.png"); + h.app.run("render.export", json!({"job":h.app.render_workspace.view.completed,"path":path})).unwrap(); + let retained = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + assert_eq!(std::fs::read(path).unwrap(), retained.png()); + // A final can arrive after the panel read a still-running status. The cached + // completed ID deliberately remains the old job until publication is sampled. + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(displayed_image(&h.app).unwrap().preview.is_none()); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().job, second); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free, "a subsequent status refresh must not refit the new final"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn cancelling_a_preview_returns_to_the_final_image_without_resetting_pan_or_export() { + let mut h = Harness::new(); + let ctx = egui::Context::default(); + let final_job = completed_preview(&mut h, [30, 50, 70]); + h.app.render_workspace.view.completed = Some(final_job); + h.app.render_workspace.view.job = Some(final_job); + cache_render_images(&mut h.app, &ctx); + let frame = h.app.session.render_job_handle(final_job).unwrap().frame().unwrap().unwrap(); + let reply = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap(); + let pending = serde_json::from_value(reply["job"].clone()).unwrap(); + h.app.render_workspace.view.job = Some(pending); + let mut info = PreviewInfo { frame_sequence: 1, samples_per_pixel: 1, frame: frame.info.clone() }; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_none(), "a different job's checkpoint must be ignored"); + info.frame.job = pending; + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + remember_displayed_job(&mut h.app, false); + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_camera.target.x = 12.0; + h.app.render_workspace.view.result_camera.distance = 87.0; + let camera = h.app.render_workspace.view.result_camera; + h.app.run("render.cancel", json!({"job":pending})).unwrap(); + cache_render_images(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + assert_eq!(displayed_image(&h.app).unwrap().info.job, final_job); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + assert_eq!(h.app.render_workspace.view.completed, Some(final_job)); + assert!(h.app.run("render.export", json!({"job":pending,"path":h.dir.join("not-final.png")})).is_err()); + let path = h.dir.join("after-preview-cancel.png"); + h.app.run("render.export", json!({"job":final_job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + // Document adoption must also release a provisional texture without leaking it into a tab. + cache_preview_frame(&mut h.app, &ctx, &info, frame.png()); + assert!(h.app.render_workspace.preview_image.is_some()); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(displayed_image(&h.app).is_none()); + assert!(h.app.render_workspace.preview_image.is_none()); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn result_framing_fits_both_axes_and_actual_size_respects_display_pixels() { + let canvas = egui::Rect::from_min_size(egui::pos2(40.0, 80.0), egui::vec2(800.0, 500.0)); + for size in [[1920, 1080], [100, 4000], [16, 16]] { + for dpi in [1.0, 1.5, 2.0] { + let fit = result_camera(size, canvas, dpi, ResultScale::Fit); + assert!(fit.is_valid()); + let fitted = result_rect(fit, size, canvas); + assert!(canvas.contains_rect(fitted), "{size:?} at {dpi}: {fitted:?}"); + assert_eq!(fitted.center(), canvas.center()); + let actual = result_rect(result_camera(size, canvas, dpi, ResultScale::Actual), size, canvas); + assert!((actual.width() * dpi - size[0] as f32).abs() < 0.01); + assert!((actual.height() * dpi - size[1] as f32).abs() < 0.01); + } + } +} + +#[test] +fn result_canvas_paints_large_capture_reports_staleness_and_preserves_export() { + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let preview = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let frame = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap(); + let draw = |app: &mut SolveApp| { + let mut out = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(app, ui), + ); + out.textures_delta.clear(); + out + }; + let out = draw(&mut h.app); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let current = h.app.tr("render.result_current"); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == current)); + let identity = format!("{}:{}:{}", job.session, job.serial, job.generation); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text().contains(&identity))); + let image_bounds = ctx + .tessellate(out.shapes, out.pixels_per_point) + .iter() + .filter_map(|p| match &p.primitive { + egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id => { + Some(mesh.vertices.iter().fold(egui::Rect::NOTHING, |r, v| r.union(egui::Rect::from_min_max(v.pos, v.pos)))) + } + _ => None, + }) + .fold(egui::Rect::NOTHING, |a, b| a.union(b)); + assert!(image_bounds.width() > 240.0 && image_bounds.height() > 240.0, "{image_bounds:?}"); + assert_eq!(h.app.cam, preview); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.session.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); + let out = draw(&mut h.app); + assert!(crate::test_support::text_shapes(&out).any(|t| t.galley.text() == h.app.tr("render.image_stale"))); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().scene_generation, frame.info.scene_generation); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), id); + let path = h.dir.join("result-canvas.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); +} + +#[test] +fn result_navigation_uses_shared_pan_zoom_and_leaves_product_camera_unchanged() { + use egui::{Event, Key, Modifiers, PointerButton, vec2}; + let mut h = Harness::new(); + let ctx = crate::fonts::test_context(); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.completed = Some(job); + h.app.render_workspace.view.result = true; + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.ui.perspective = true; + h.app.preferences.smooth_wheel_zoom = false; + h.app.preferences.zoom_reverse = false; + let preview = h.app.cam; + let draft = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let dirty = h.app.render_workspace.view.dirty; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let mut time = 0.0; + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let fitted = h.app.render_workspace.view.result_camera; + let p = h.app.viewport.rect.unwrap().center() + vec2(80.0, 20.0); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p)]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 3.0), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert!(h.app.render_workspace.view.result_camera.distance < fitted.distance); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + let before_pan = h.app.render_workspace.view.result_camera.target; + let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![space(true), Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], + ); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(p + vec2(40.0, -20.0))]); + nav_frame( + &mut h.app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![ + Event::PointerButton { pos: p + vec2(40.0, -20.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + space(false), + ], + ); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_pan); + assert_eq!(h.app.render_workspace.view.result_camera.pitch, fitted.pitch); + assert_eq!(h.app.render_workspace.view.result_camera.yaw, fitted.yaw); + let before_key = h.app.render_workspace.view.result_camera.target; + assert!(crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::CTRL, false)); + assert_ne!(h.app.render_workspace.view.result_camera.target, before_key); + assert!(!crate::navigation::view_key(&mut h.app, &ctx, Key::ArrowRight, Modifiers::NONE, false)); + for command in ["view.fit", "view.home"] { + h.app.render_workspace.view.result_camera.target.x += 20.0; + h.app.run(command, json!({})).unwrap(); + nav_frame(&mut h.app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + assert_eq!(h.app.render_workspace.view.result_camera, fitted); + } + assert_eq!(h.app.cam, preview); + assert!(h.app.ui.perspective); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), draft); + assert_eq!(h.app.render_workspace.view.dirty, dirty); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_params(&h.app).unwrap()["settings"]["camera"], json!(preview)); +} + +#[test] +fn clicked_result_controls_switch_canvas_and_frame_without_changing_the_setup() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1400})); + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let result = h.app.tr("render.result_title").to_string(); + h.step(&json!({"widget":result})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.result); + h.step(&json!({"widget":"100%"})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Actual); + let fit = h.app.tr("render.result_fit").to_string(); + h.step(&json!({"widget":fit})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Fit); + let preview = h.app.tr("render.result_preview").to_string(); + h.step(&json!({"widget":preview})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn image_method_requests_never_fall_back_or_mix_cpu_and_gpu_options() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = h.app.cam.distance * 3.0; + h.app.render_workspace.view.raytrace.exposure_ev = f64::NAN; + h.app.render_workspace.view.samples = 256; + h.app.render_workspace.view.max_depth = 12; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.draft.exposure_ev = 0.0; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "never-opened.hdr".into() }; + h.app.render_workspace.view.studio.denoise = true; + h.app.render_workspace.view.studio.lens_enabled = true; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "never-opened-cpu.hdr".into() }; + let params = image_params(&h.app).unwrap(); + assert_eq!(params["settings"]["camera"], json!(h.app.cam)); + assert_eq!(params["settings"]["exposure_ev"], 0.0); + for key in ["progressive", "samples", "max_depth", "seed", "integrator", "raytrace", "environment", "lighting", "tone_map", "lens", "denoise"] { + assert!(params.get(key).is_none(), "raster must omit {key}"); + } + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + assert!(image_params(&h.app).is_err(), "missing GPU cannot silently render on CPU"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "unsupported CPU options or host must be refused"); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_params(&h.app).is_err()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_cpu_controls_check_and_start_the_same_capture_and_keep_it_exportable() { + use solidcraft_engine::render::job::{CpuHost, Phase}; + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.dirty = true; + h.frames(3); + let available = image_host(&h.app, ImageMethod::CpuRaytrace).is_ok(); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-cpu"}})).unwrap(); + if !available { + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(image_params(&h.app).is_err()); + return; + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.step(&json!({"click":{"handle":"render:aa"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:aa-4"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 4); + h.app.render_workspace.view.raytrace.preset = Some(LightingPreset::WarmCool); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let numeric = image_params(&h.app).unwrap(); + assert_eq!(numeric["settings"]["job"]["method"], "cpu_raytrace"); + assert!(numeric.get("raytrace").is_none()); + let numeric_check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":numeric_check})).unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, numeric); + let reflected = h.app.session.world_state().bodies.first().unwrap().name.clone(); + let reflection_section = format!("dialog:section:{}", h.app.tr("render.cpu_reflections")); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-body"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-reflection-add"}})).unwrap(); + h.step(&json!({"click":{"handle":format!("render:cpu-reflection-mode:{reflected}")}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render.cpu_reflection_mirror"}})).unwrap(); + assert_eq!( + h.app.render_workspace.view.raytrace.reflections.as_ref().unwrap().bodies[0].mode, + solidcraft_engine::render::job::ReflectionMode::Mirror + ); + h.step(&json!({"click":{"handle":reflection_section}})).unwrap(); + let hdr_path = h.dir.join("cpu-captured.hdr"); + let mut hdr = 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 1 +X 2\n".to_vec(); + hdr.extend_from_slice(&[128, 128, 128, 129, 128, 128, 128, 129]); + std::fs::write(&hdr_path, &hdr).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, hdr_path.to_string_lossy().into_owned()).unwrap(); + h.app.render_workspace.view.cpu.samples = 4; + h.app.render_workspace.view.result = true; + h.app.render_workspace.view.result_camera.distance = 42.0; + h.frames(2); + let camera = h.app.cam; + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let params = image_params(&h.app).unwrap(); + let preflight = h.app.session.execute("render.preflight", ¶ms).unwrap(); + assert_eq!(preflight["resolved"]["executor"], "cpu-raytrace"); + let check = h.app.tr("cmd.render_preflight").to_string(); + h.step(&json!({"widget":check})).unwrap(); + assert_eq!(image_params(&h.app).unwrap(), params); + let checked = h.app.render_workspace.view.cpu.checked.as_ref().unwrap(); + assert_eq!(checked.request, params); + assert_eq!(checked.environment, preflight["environment"]); + let start = h.app.tr("render.image_start").to_string(); + h.step(&json!({"widget":start})).unwrap(); + let id = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + // The job owns the source bytes captured by Start, even if the file changes. + std::fs::write(&hdr_path, b"changed after capture").unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(json!(status.environment), preflight["environment"]); + assert_eq!(status.progress.phase, Phase::Completed); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(json!(status.request.camera), params["settings"]["camera"]); + assert_eq!(json!(status.request.raytrace), params["raytrace"]); + assert_eq!(status.request.width, 16); + assert_eq!(status.request.height, 16); + h.frames(3); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let frame = handle.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + let path = h.dir.join("cpu-result-canvas.png"); + h.app.run("render.export", json!({"job":id,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + h.app.render_workspace.view.transparent = true; + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_opaque_required"))); + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.primary_samples = 3; + assert!(image_params(&h.app).is_err()); + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.area_lights = Some(Vec::new()); + assert_eq!(image_params(&h.app).unwrap()["raytrace"]["area_lights"], json!([])); +} + +fn async_export_fixture() -> (Harness, solidcraft_engine::render::job::JobId) { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + h.app.session.mark_saved(); + let job = completed_preview(&mut h, [200, 210, 220]); + (h, job) +} + +#[test] +fn delayed_image_export_holds_its_document_without_changing_history() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("delayed.png"); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy() && !path.exists()); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], true); + crate::documents::new_design(&mut h.app); + let other = h.app.session.doc.clone(); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.docs.active, 0, "upstream holds tab changes while a picker is pending"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["file_dialog_open"], false); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert_eq!(&std::fs::read(&path).unwrap()[..8], b"\x89PNG\r\n\x1a\n"); + crate::documents::switch(&mut h.app, 0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn delayed_image_export_cancel_and_overwrite_choice_preserve_existing_files() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("existing.png"); + std::fs::write(&path, b"existing contents").unwrap(); + let doc = h.app.session.doc.clone(); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!h.app.file_picker_busy()); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents"); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + h.app.render_workspace.view.overwrite = true; + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(std::fs::read(&path).unwrap(), b"existing contents", "a later checkbox change is not overwrite consent for the pending export"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "completed"); +} + +#[test] +fn delayed_image_export_never_substitutes_a_newer_retained_image() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("old-image.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + let newer = completed_preview(&mut h, [20, 30, 40]); + h.app.render_workspace.view.completed = Some(newer); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists(), "the evicted requested image must fail instead of exporting the newer image"); + assert!(matches!(&h.app.status, Some((_, _, true)))); + assert_eq!(h.app.render_workspace.view.completed, Some(newer)); + let newer_path = h.dir.join("new-image.png"); + h.app.run("render.export", json!({"job":newer,"path":newer_path})).unwrap(); + assert!(newer_path.is_file()); +} + +#[test] +fn delayed_image_export_holds_close_and_new_document_until_cancel() { + use crate::picker_test_support::{Slot, save}; + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("closed.png"); + let ctx = crate::fonts::test_context(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + crate::documents::new_design(&mut h.app); + crate::documents::close(&mut h.app, 0, true); + let other = h.app.session.doc.clone(); + assert_eq!(h.app.docs.count(), 1); + assert!(h.app.file_picker_busy()); + *slot.borrow_mut() = Some(None); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!path.exists() && !h.app.file_picker_busy()); + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); +} + +#[test] +fn delayed_image_export_refuses_an_internally_replaced_document_even_with_overwrite() { + use crate::picker_test_support::{Slot, save}; + for overwrite in [false, true] { + let (mut h, job) = async_export_fixture(); + let path = h.dir.join("keep.png"); + std::fs::write(&path, b"keep this file").unwrap(); + let slot: Slot = Default::default(); + save(&mut h.app, &slot); + export_image(&mut h.app, job, overwrite); + assert!(h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":[1,2,3]})).is_err()); + // Internal host/session changes are outside the input hold; never export them by accident. + h.app.session.execute("appearance.assign", &json!({"bodies":["Body1"],"color":[1,2,3]})).unwrap(); + let changed = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.revision); + *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &crate::fonts::test_context()); + assert_eq!(std::fs::read(path).unwrap(), b"keep this file"); + assert!(Arc::ptr_eq(&changed, &h.app.session.doc)); + assert_eq!((h.app.session.undo.len(), h.app.session.revision), history); + assert!(matches!(&h.app.status, Some((_, _, true)))); + } +} + +/// One frame of either the modelling viewport or the Render preview, over the same rectangle. +fn nav_frame(app: &mut crate::SolveApp, ctx: &egui::Context, render: bool, time: &mut f64, mods: egui::Modifiers, events: Vec) { + *time += 1.0 / 60.0; + let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if render { + show(app, ui); + } else { + crate::viewport::show(app, ui); + } + }); + out.textures_delta.clear(); +} + +fn nav_app(render: bool, preset: &str, around: crate::prefs::OrbitAround) -> crate::SolveApp { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + let mut app = crate::SolveApp::new(s, crate::Services::default()); + if render { + enter(&mut app, true).unwrap(); + assert!(active(&app)); + } + app.preferences.nav = preset.into(); + app.preferences.orbit_around = around; + app.preferences.zoom_to_cursor = true; + app.ui.perspective = true; + let mut cam = Camera { fov: 0.6, ..Default::default() }; + cam.set_view(solidcraft_engine::render::StandardView::Iso); + cam.fit(&solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds); + app.cam = cam; + app +} + +/// #1454: the same mouse, wheel and modifier input moves the Render preview's camera exactly as +/// it moves the modelling viewport's, under every navigation preset and Orbit around setting. +#[test] +fn render_preview_navigates_like_the_modelling_viewport_in_every_preset() { + use egui::{Event, Modifiers, PointerButton, pos2, vec2}; + let none = Modifiers::NONE; + let chords = [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT]; + let arounds = [crate::prefs::OrbitAround::ViewCentre, crate::prefs::OrbitAround::Cursor, crate::prefs::OrbitAround::Origin]; + for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { + for around in arounds { + let (design_ctx, render_ctx) = (crate::fonts::test_context(), crate::fonts::test_context()); + let mut design = nav_app(false, preset, around); + let mut render = nav_app(true, preset, around); + let (mut design_time, mut render_time) = (0.0, 0.0); + let mut both = |events: Vec, mods: Modifiers, design: &mut crate::SolveApp, render: &mut crate::SolveApp| { + nav_frame(design, &design_ctx, false, &mut design_time, mods, events.clone()); + nav_frame(render, &render_ctx, true, &mut render_time, mods, events); + }; + both(vec![], none, &mut design, &mut render); + assert_eq!(design.viewport.rect, render.viewport.rect); + // Presses start on empty space in both workspaces, and the wheel + // turns over the model, so zoom to the cursor anchors on its surface. + let empty = pos2(90.0, 520.0); + let proj = crate::viewport::projection(&design, design.viewport.rect.unwrap()); + assert!(crate::viewport::pick(&design, &proj, empty).is_empty()); + let model = proj.to_screen(design.cam.target).unwrap(); + assert!(!crate::viewport::pick(&design, &proj, model).is_empty()); + let mut moved = 0; + for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { + for mods in chords { + let before = design.cam; + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerButton { pos: empty, button, pressed: true, modifiers: mods }], mods, &mut design, &mut render); + let mut at = empty; + for _ in 0..5 { + at += vec2(14.0, -9.0); + both(vec![Event::PointerMoved(at)], mods, &mut design, &mut render); + } + both(vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: mods }], mods, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_eq!(design.cam, render.cam, "{preset} {around:?}: {button:?} drag with {mods:?}"); + moved += usize::from(design.cam != before); + // Let any snap settle and start the next gesture from the same view. + design.cam = render.cam; + } + } + assert!(moved >= 2, "{preset}: the preset's drags move the camera ({moved})"); + // Wheel over the model, then modifier-only motion (Touchpad: Shift pans, Alt orbits). + let before = design.cam; + both(vec![Event::PointerMoved(model)], none, &mut design, &mut render); + let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; + both(vec![wheel], none, &mut design, &mut render); + for _ in 0..30 { + both(vec![], none, &mut design, &mut render); + } + assert_ne!(design.cam, before, "{preset}: the wheel zooms"); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: wheel zoom to the cursor"); + for mods in [Modifiers::SHIFT, Modifiers::ALT] { + both(vec![Event::PointerMoved(empty)], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty + vec2(25.0, 15.0))], mods, &mut design, &mut render); + both(vec![Event::PointerMoved(empty)], none, &mut design, &mut render); + assert_eq!(design.cam, render.cam, "{preset} {around:?}: modifier motion with {mods:?}"); + } + assert!(render.session.selection.is_empty(), "camera navigation must not select"); + } + } +} + +/// #1454: Fit (F6), a middle double-click, and the axis view's and navigation cube's Home and +/// view controls all work in the Render workspace, framing the product scene. +#[test] +fn render_workspace_view_keys_double_middle_click_and_navigators_work() { + for style in [crate::prefs::NavigatorStyle::Axes, crate::prefs::NavigatorStyle::Cube] { + let mut h = Harness::new(); + h.app.preferences.navigator_style = style; + h.app.preferences.look_at_anim = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Product"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.frames(3); + let mut home = h.app.cam; + home.set_view(solidcraft_engine::render::StandardView::Iso); + let off = |h: &mut Harness| { + h.app.cam.yaw += 0.7; + h.app.cam.pitch = 0.1; + h.app.cam.distance *= 3.0; + h.app.cam.target.x += 25.0; + h.frames(2); + }; + // F6 fits, keeping the direction. + off(&mut h); + let before = h.app.cam; + h.step(&json!({"key":"F6"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (before.yaw, before.pitch, before.roll, before.up), + "{style:?}: F6 retains orientation" + ); + assert!(h.app.cam.distance < before.distance, "{style:?}: F6 frames the product"); + assert_product_fits_canvas(&h.app); + // A middle double-click goes Home. + off(&mut h); + let centre = h.app.viewport.rect.unwrap().center(); + h.step(&json!({"click":[centre.x, centre.y], "double":true, "button":"middle"})).unwrap(); + h.settle(); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (home.yaw, home.pitch, home.roll, home.up), + "{style:?}: middle double-click" + ); + assert_product_fits_canvas(&h.app); + // The navigator's Home control. + off(&mut h); + let handle = match style { + crate::prefs::NavigatorStyle::Axes => "axis_view:home", + crate::prefs::NavigatorStyle::Cube => "navigation_cube:control:home", + }; + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.settle(); + assert!( + (h.app.cam.yaw - home.yaw).abs() < 1e-6 && (h.app.cam.pitch - home.pitch).abs() < 1e-6, + "{style:?}: navigator Home turns to the home view" + ); + // A standard view from the navigator. + h.step(&json!({"click":{"handle":"axis_view:z"}})).unwrap(); + h.settle(); + assert!(h.app.cam.back().dot(solidcraft_engine::geom::Vec3::Z) > 0.999, "{style:?}: view from +Z, got {:?}", h.app.cam.back()); + assert!(h.app.session.selection.is_empty()); + } +} + +/// #1464: a maximised 4K or 5K window is past the preview's pixel budget. The preview draws +/// smaller at the same aspect instead of refusing every frame. +#[test] +fn four_and_five_k_viewports_preview_downscaled_within_the_limits() { + use solidcraft_engine::render::*; + for samples in [1, 4, 16] { + let host = host_executor(16384, true, samples).unwrap(); + let mut s = Session::default(); + s.set_render_viewport(Some(host.clone())).unwrap(); + let request = |width, height| RenderRequest { + backend: None, + mode: RenderMode::Preview, + operation: RenderOperation::Viewport, + width, + height, + format: None, + features: vec![RenderFeature::Pbr], + policy: Default::default(), + }; + if samples <= 4 { + assert_eq!(preview_size(s.render_viewport(), (1920, 1080)), (1920, 1080), "fits: drawn at full size"); + } + // 16× MSAA's scratch cost brings even 1080p under the budget. + let sizes: &[(u64, u64)] = if samples == 16 { &[(1920, 1080), (3840, 2160), (5120, 2880)] } else { &[(3840, 2160), (5120, 2880)] }; + for &full in sizes { + assert!(resolve_request(&[s.render_backend()], &request(full.0, full.1)).is_err(), "{full:?} at full size is over the limit"); + let (w, h) = preview_size(s.render_viewport(), full); + assert!(w < full.0 && h < full.1 && w * h <= host.limits.max_pixels, "{full:?} -> {w}x{h}"); + assert!((w as f64 / h as f64 - 16.0 / 9.0).abs() < 0.01, "{w}x{h} keeps the aspect"); + let resolved = resolve_request(&[s.render_backend()], &request(w, h)).unwrap(); + assert_eq!(resolved.executor.as_str(), "gpu-viewport"); + assert!(resolved.estimated_scratch_bytes <= host.limits.max_scratch_bytes); + } + } + assert_eq!(preview_size(None, (5120, 2880)), (5120, 2880), "no executor: resolution reports it"); +} + +/// Backend failures must remain readable in the fixed-width Render panel, not +/// disappear into an ellipsis before the reason and recovery guidance are shown. +#[test] +fn backend_diagnostics_wrap_without_elision_in_bounded_image_controls() { + fn collect<'a>(shape: &'a egui::Shape, texts: &mut Vec<&'a egui::epaint::TextShape>) { + match shape { + egui::Shape::Text(text) => texts.push(text), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, texts)), + _ => {} + } + } + for mode in ["floating", "compact"] { + for dark in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1400,"height":1800})); + h.app.run("view.layout", json!({"mode":mode})).unwrap(); + enter(&mut h.app, true).unwrap(); + let reason = "The selected viewport adapter has no compatible Vulkan path device. Images remain available on the CPU; keep the original design and review the driver before retrying."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + h.frames(3); + let expected = format!("{}: {reason}", h.app.tr("render.gpu_path_failed")); + let mut out = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1800.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + ui.set_max_width(285.0); + image_controls(&mut h.app, ui); + }, + ); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|shape| collect(&shape.shape, &mut texts)); + { + let message = &expected; + let text = texts.iter().find(|text| text.galley.job.text == *message).expect("the complete diagnostic is painted"); + assert!(!text.galley.elided, "{mode}, dark={dark}: {message}"); + assert!(text.galley.rows.len() > 1, "long messages must wrap in the narrow panel"); + assert!(text.galley.rect.width() <= 285.0, "the message must not expand the panel"); + } + } + } +} + +#[test] +fn gpu_material_recipes_use_exact_linear_absorption_without_changing_saved_appearance() { + use solidcraft_engine::doc::appearance_pack::{GlassBoundary, Recipe, STARTER_PACK}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + h.app.session.mark_saved(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(preset.id).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding]; + let mut params = json!({"progressive":true}); + materials::params(&h.app, &mut params).unwrap(); + let wire = ¶ms["raytrace"]["dielectrics"][0]; + assert_eq!(wire["body_name"], "Optics"); + assert_eq!(wire["ior"], recipe.dielectric_ior); + let [r, g, b]: [f64; 3] = serde_json::from_value(wire["absorption_per_mm"].clone()).unwrap(); + let medium = solidcraft_engine::render::transmission::Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + let transmitted = medium.attenuation(recipe.reference_path_mm).unwrap(); + for (actual, expected) in [transmitted.x, transmitted.y, transmitted.z].into_iter().zip(recipe.transmission_linear_rgb) { + assert!((actual - expected).abs() < 1e-12, "the actual optical consumer must reproduce the recipe's linear transmittance"); + } + match recipe.boundary { + GlassBoundary::Closed => { + assert_eq!(wire["boundary"], "closed_mesh"); + assert_eq!(wire["thickness_mm"], 0.0); + } + GlassBoundary::Thin { thickness_mm } => { + assert_eq!(wire["boundary"], "thin_sheet"); + assert_eq!(wire["thickness_mm"], thickness_mm); + } + } + assert!(wire.get("opacity").is_none()); + count += 1; + } + assert_eq!(count, 6); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.materials.enabled = false; + let mut raster = json!({}); + materials::params(&h.app, &mut raster).unwrap(); + assert!(raster.get("raytrace").is_none()); +} + +#[test] +fn gpu_material_identity_requires_explicit_revalidation_and_never_retargets() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.coat_enabled = true; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings = vec![binding.clone()]; + materials::params(&h.app, &mut json!({})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[20,0,0],"body_name":"Other","operation":"new"})).unwrap(); + let scene = h.app.run("render.scene", json!({})).unwrap(); + let target: materials::Target = + serde_json::from_value(scene["bodies"].as_array().unwrap().iter().find(|body| body["name"] == "Other").unwrap().clone()).unwrap(); + let mut moved = materials::Binding::new(target.clone(), &h.app); + moved.coat_enabled = true; + h.app.render_workspace.view.materials.bindings = vec![moved.clone()]; + h.app.run("browser.visibility", json!({"items":["Optics"],"visible":false})).unwrap(); + assert!(materials::params(&h.app, &mut json!({})).is_err()); + assert!(materials::revalidate(&mut h.app, &mut moved).is_err(), "a surviving body with a new ordinal must be selected explicitly"); + assert_eq!(moved.target, target); + let scene = h.app.run("render.scene", json!({})).unwrap(); + assert_eq!(scene["bodies"][0]["name"], "Other"); + assert_ne!(scene["bodies"][0]["ordinal"], target.ordinal); + binding.target.name = "Different body".into(); + assert!(materials::revalidate(&mut h.app, &mut binding).is_err()); + assert_eq!(binding.target.name, "Different body"); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); +} + +#[test] +fn clicked_gpu_glass_recipe_stays_temporary_and_blocks_cpu_rendering() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + h.app.session.mark_saved(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.frames(3); + let doc = h.app.session.doc.clone(); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:render:material-body-0"}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let glass = h.app.tr("render.appearance_editor.glass").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{glass}")}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.material_custom")})).unwrap(); + h.step(&json!({"click":{"handle":"render:glass:starter.glass.amber-tint"}})).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert!(binding.glass_enabled && !binding.coat_enabled && !binding.maps_enabled); + assert_eq!(binding.glass.recipe, Some("starter.glass.amber-tint")); + assert_eq!(binding.target.name, "Optics"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + assert!(image_params(&h.app).is_err(), "CPU must not silently ignore active GPU material assignments"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn clicked_gpu_material_at_assignment_limit_edits_existing_but_cannot_add_another_body() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1,"body_name":"Optics"})).unwrap(); + h.app.run("solid.pattern.rectangular", json!({"bodies":["Optics"],"dir1":[1,0,0],"count1":129,"spacing1":3})).unwrap(); + let targets: Vec = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"].clone()).unwrap(); + assert_eq!(targets.len(), 129); + h.app.session.mark_saved(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.render_workspace.view.materials.bindings = targets.iter().skip(1).cloned().map(|target| materials::Binding::new(target, &h.app)).collect(); + h.frames(3); + let title = h.app.tr("render.material_title").to_string(); + h.step(&json!({"click":{"handle":format!("dialog:section:{title}")}})).unwrap(); + let refresh = h.app.tr("render.material_refresh").to_string(); + h.step(&json!({"widget":refresh})).unwrap(); + let choose = h.app.tr("render.material_choose_body").to_string(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[1].ordinal)}})).unwrap(); + let add = h.app.tr("render.material_add").to_string(); + h.step(&json!({"widget":add})).unwrap(); + let include = h.app.tr("render.material_binding_enable").to_string(); + h.step(&json!({"widget":include})).unwrap(); + assert!(!h.app.render_workspace.view.materials.bindings[0].enabled, "the existing assignment remains editable at the limit"); + assert!(h.app.render_workspace.view.materials.bindings.iter().skip(1).all(|binding| binding.enabled)); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + + // The first scene body has no assignment: selecting it cannot create a 129th entry. + h.step(&json!({"widget":refresh})).unwrap(); + h.step(&json!({"widget":choose})).unwrap(); + h.step(&json!({"click":{"handle":format!("dialog:list:render:material-body-{}", targets[0].ordinal)}})).unwrap(); + h.step(&json!({"widget":add})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 128); + assert!(h.app.render_workspace.view.materials.bindings.iter().all(|binding| binding.target != targets[0])); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.session.is_dirty()); +} + +#[test] +fn cpu_reflection_controls_preserve_exact_targets_and_engine_bounds() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let reflections = h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap(); + assert_eq!(reflections.bodies.len(), 1); + reflections.max_bounces = 8; + reflections.samples = 64; + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"rough_specular"}])); + assert_eq!(params["raytrace"]["reflections"]["max_bounces"], 8); + assert_eq!(params["raytrace"]["reflections"]["samples"], 64); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 9; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().max_bounces = 8; + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 65; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.reflections.as_mut().unwrap().samples = 64; + h.app.session.visibility.hidden_bodies.push("Reflector".into()); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + assert!(h.app.render_workspace.view.raytrace.reflections.is_none()); + assert!(cpu::set_reflection(&mut h.app, "Missing", Some(ReflectionMode::Mirror)).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn cpu_reflection_binding_requires_confirmation_and_never_follows_a_reused_name() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("solid.box", json!({"length":5,"width":5,"height":5,"body_name":"Other"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")) + ); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err(), "confirmation cannot move a binding to a different feature"); + let before = json!(h.app.render_workspace.view.raytrace.reflections); + for mode in [ReflectionMode::Mirror, ReflectionMode::RoughSpecular] { + assert!(cpu::set_reflection(&mut h.app, "Reflector", Some(mode)).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before, "a stale row's mode cannot rebind its body"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + } + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); + // Isolate document identity: the cloned document has the same bodies, IDs and revision. + let previous_doc = h.app.session.doc.clone(); + let previous_revision = h.app.session.revision; + h.app.session = Session::new((*previous_doc).clone()); + h.app.session.revision = previous_revision; + assert!(!Arc::ptr_eq(&previous_doc, &h.app.session.doc)); + assert!(cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); +} + +#[test] +fn cpu_interactive_reflection_binding_accepts_appearance_and_render_intent_without_qualifying_final() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let world = h.app.session.world_state(); + let mesh = world.body("Reflector").unwrap().cached_mesh().unwrap(); + let document = h.app.session.doc.clone(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Reflector"],"color":"#123456"})).unwrap(); + assert!(!Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(Arc::ptr_eq(&mesh, &h.app.session.world_state().body("Reflector").unwrap().cached_mesh().unwrap())); + h.app.run("render.settings.set", json!({"name":"Interactive target proof","set":{"width":800,"height":600}})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.world_state())); + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-interactive-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.25; + h.app.render_workspace.view.cpu.intensity = 2.0; + let before = json!(h.app.render_workspace.view.raytrace.reflections); + let mut interactive = json!({}); + cpu::params_interactive(&h.app, &mut interactive).unwrap(); + assert_eq!(interactive["raytrace"]["reflections"]["bodies"], json!([{"body":"Reflector","mode":"mirror"}])); + assert_eq!(interactive["raytrace"]["exposure_ev"], 1.5); + assert_eq!(interactive["environment"]["rotation_radians"], 0.25); + assert_eq!(interactive["environment"]["expected_sha256"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert_eq!(json!(h.app.render_workspace.view.raytrace.reflections), before); + assert!( + cpu::params(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale")), + "Interactive refresh cannot qualify final Check/Start" + ); + assert!( + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).is_err(), + "mode changes still require explicit confirmation" + ); +} + +#[test] +fn cpu_interactive_binding_keeps_cold_meshes_cold_and_refuses_another_world_until_confirmation() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + let retained = Arc::strong_count(&world); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none(), "request lowering must not tessellate"); + assert_eq!(Arc::strong_count(&world), retained, "the binding must not retain the evaluated world"); + h.app.session.execute("appearance.assign", &json!({"bodies":["Reflector"],"color":"#654321"})).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(world.body("Reflector").unwrap().cached_mesh().is_none()); + h.app.session.execute("solid.box", &json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + cpu::revalidate(&mut h.app, "Reflector").unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + cpu::params(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_interactive_binding_refuses_reused_names_and_same_revision_in_a_new_document() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + h.app.run("solid.box", json!({"length":3,"width":3,"height":3,"corner":[30,0,0],"body_name":"Other","operation":"new"})).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("body.rename", json!({"body":"Reflector","name":"Original"})).unwrap(); + h.app.run("body.rename", json!({"body":"Other","name":"Reflector"})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); + assert!(cpu::revalidate(&mut h.app, "Reflector").is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let uid = h.app.session.uid; + h.app.session = Session::new((*document).clone()); + h.app.session.revision = revision; + assert_ne!(h.app.session.uid, uid); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err()); +} + +#[test] +fn cpu_interactive_binding_refuses_moved_occurrences_and_hidden_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.run("component.create", json!({"name":"Part","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let name = world.bodies[0].name.clone(); + let mesh = world.bodies[0].mesh(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let moved = h.app.session.world_state(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(!Arc::ptr_eq(&mesh, &moved.bodies[0].mesh())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "same creator and name cannot certify a moved instance"); + cpu::revalidate(&mut h.app, &name).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + h.app.session.visibility.hidden_bodies.push(name); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_body_missing"))); +} + +#[test] +fn cpu_interactive_binding_refuses_deleted_then_recreated_equal_looking_targets() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let world = h.app.session.world_state(); + let feature = world.body("Reflector").unwrap().feature; + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + h.app.run("timeline.delete", json!({"feature":feature.to_string()})).unwrap(); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + assert!(h.app.session.world_state().body("Reflector").is_some(), "the recreated case must actually reuse the selected name"); + assert!(!Arc::ptr_eq(&world, &h.app.session.world_state())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).is_err(), "identical names/dimensions cannot certify recreated geometry"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + cpu::set_reflection(&mut h.app, "Reflector", None).unwrap(); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::Mirror)).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); +} + +#[test] +fn cpu_environment_controls_keep_wire_schemas_separate_without_reading_files() { + let mut h = Harness::new(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-opened-by-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + let mut hdr = json!({}); + cpu::params(&h.app, &mut hdr).unwrap(); + assert_eq!( + hdr["environment"], + json!({"path":"not-opened-by-ui.hdr","expected_sha256":h.app.render_workspace.view.cpu.hdr.resource().unwrap(),"rotation_radians":std::f64::consts::FRAC_PI_2,"intensity":2.0,"samples":64}) + ); + assert!(hdr["raytrace"].get("environment").is_none()); + for gpu_key in ["progressive", "tone_map", "denoise", "lighting", "lens"] { + assert!(hdr.get(gpu_key).is_none()); + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.2, 0.4, 0.8]; + let mut constant = json!({}); + cpu::params(&h.app, &mut constant).unwrap(); + assert!(constant.get("environment").is_none()); + assert_eq!(constant["raytrace"]["environment"], json!({"color":[0.2,0.4,0.8],"intensity":2.0})); + assert!(h.app.render_workspace.view.raytrace.environment.is_none(), "request building must not mutate the editable base"); + h.app.render_workspace.view.cpu.color[0] = f64::NAN; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.samples = 3; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.samples = 16; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("bad\npath.hdr"); + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + let mut none = json!({}); + cpu::params(&h.app, &mut none).unwrap(); + assert!(none.get("environment").is_none()); + assert!(none["raytrace"].get("environment").is_none()); +} + +#[test] +fn cpu_light_controls_preserve_hidden_spot_fields_and_validate_runtime_bounds() { + use solidcraft_engine::render::job::{DirectionalLightOptions, PunctualLightOptions, SpotConeOptions}; + let mut h = Harness::new(); + 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.raytrace.punctual_lights = Some(vec![PunctualLightOptions { + position_mm: [0.0, 0.0, 100.0], + color: [1.0, 0.5, 0.25], + intensity: 4.0, + reference_distance_mm: 100.0, + minimum_distance_mm: 0.01, + cone: None, + }]); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!(params["raytrace"]["lights"][0]["intensity"], 2.0); + assert_eq!(params["raytrace"]["punctual_lights"][0]["reference_distance_mm"], 100.0); + assert!(params.get("lighting").is_none(), "CPU must not emit GPU studio lighting"); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0; 3]; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.lights.as_mut().unwrap()[0].direction = [0.0, 0.0, 1.0]; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 101.0; + assert!(cpu::params(&h.app, &mut json!({})).is_err()); + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].minimum_distance_mm = 0.01; + h.app.render_workspace.view.raytrace.punctual_lights.as_mut().unwrap()[0].cone = + Some(SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.1, outer_half_angle_radians: 0.2 }); + let mut params = json!({}); + cpu::params(&h.app, &mut params).unwrap(); + assert_eq!( + params["raytrace"]["punctual_lights"][0]["cone"], + json!(h.app.render_workspace.view.raytrace.punctual_lights.as_ref().unwrap()[0].cone) + ); +} + +#[test] +fn delayed_cpu_hdr_picker_cannot_write_into_another_document_or_revision() { + use crate::picker_test_support::{Slot, open}; + for other_document in [false, true] { + let mut h = Harness::new(); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: "original.hdr".into() }; + hdr::pick(&mut h.app, hdr::Target::Cpu); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(h.app.file_picker_busy()); + if other_document { + h.app.session = Session::default(); + } else { + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5})).unwrap(); + } + *slot.borrow_mut() = Some(Some("late.hdr".into())); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.cpu.hdr, hdr::Input::FilePending { path: "original.hdr".into() }); + } +} + +#[test] +fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host() { + use solidcraft_engine::doc::render_settings::{GpuJob, RenderJob, SkyEnvironment}; + use solidcraft_engine::render::job::{AreaLight, AreaLights, StudioLighting, Sun, ThinLens, ToneMap}; + use solidcraft_engine::render::lighting::environment::SkyGradient; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.frames(3); + h.app.session.set_render_job_host(None).unwrap(); + assert!(image_host(&h.app, ImageMethod::GpuRaytrace).is_err()); + h.step(&json!({"click":{"handle":"render:method"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:method-gpu"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + h.app.cam.fov = 0.7; + h.app.ui.perspective = true; + // The positive UI fixture uses the admitted document boundary. Coordinates + // beyond it must still refuse before a setup that cannot reopen is created. + for x in [-2e9, 2e9, 1e9_f64.next_up()] { + assert!( + AreaLights::new(&[AreaLight { center: [x, 0.0, 100.0], u: [2.0, 0.0, 0.0], v: [0.0, -3.0, 0.0], radiance: [3.0, 5.0, 7.0] }]).is_err() + ); + } + let expected = RenderSetup { + camera: h.app.cam, + exposure_ev: 1.25, + width: 48, + height: 32, + job: Some(RenderJob::GpuPath { + transparent_background: true, + options: Box::new(GpuJob { + aging: Default::default(), + nested_media: true, + volume: Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }), + adaptive: Some(solidcraft_engine::render::job::adaptive::AdaptiveSampling { + pilot_samples: 16, + min_samples: 16, + relative_error: 0.1, + absolute_error: 0.003, + coverage_error: 0.02, + }), + transmission_samples: 4, + finishing: Default::default(), + backdrop: None, + linear_exr: false, + samples: 37, + max_depth: 11, + seed: 1977, + tone_map: ToneMap::AcesFitted, + denoise: true, + lens: Some(ThinLens { aperture_radius_mm: 0.5, focus_distance_mm: 123.0 }), + lighting: Some(StudioLighting { + environment: [0.25, 0.5, 0.75], + sun: Some(Sun { direction: [2.0, 3.0, 4.0], angular_radius_rad: 0.0123456789, radiance: [11.0, 22.0, 33.0] }), + area_lights: AreaLights::new(&[AreaLight { + center: [1e9, 0.0, 100.0], + u: [2.0, 0.0, 0.0], + v: [0.0, -3.0, 0.0], + radiance: [3.0, 5.0, 7.0], + }]) + .unwrap(), + }), + environment: Some(SkyEnvironment::Sky { + gradient: SkyGradient { zenith: [0.3, 0.4, 0.5], horizon: [0.6, 0.7, 0.8], ground: [0.1, 0.2, 0.3] }, + rotation_rad: std::f64::consts::PI, + intensity: 1.75, + }), + hdr: None, + }), + }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"GPU saved","set":expected})).unwrap(); + h.app.render_workspace.view.name = "GPU saved".into(); + setups::load(&mut h.app); + let completed = h.app.render_workspace.view.completed; + let result_camera = h.app.render_workspace.view.result_camera; + h.frames(3); + h.app.run("view.render_select", json!({"kind":"sampling"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"area:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(image_params(&h.app).is_err(), "offline editing must not claim an executable GPU"); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.step(&json!({"click":{"handle":"render:setup-name"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"GPU copy"})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "GPU copy"); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "typing Save As must not reset the settings"); + assert!(h.app.render_workspace.view.dirty); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.setups["GPU copy"], expected); + h.app.render_workspace.view.seed = 8; + h.app.render_workspace.view.studio.ambient[1] = 0.125; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.render_workspace.view.name = "Raster saved".into(); + setups::save(&mut h.app).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:setups"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:setup:GPU copy"}})).unwrap(); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.completed, completed); + assert_eq!(h.app.render_workspace.view.result_camera, result_camera); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the boundary setup must reopen from JSON"); + let native = solidcraft_engine::io::write_design_container(&h.app.session.doc).unwrap(); + let reopened = solidcraft_engine::io::read_design(&native).unwrap(); + assert_eq!(reopened.render.setups["GPU copy"], expected, "the native container keeps exact numeric intent"); +} + +#[test] +fn cpu_setup_reload_preserves_unedited_numeric_options_and_explicit_empty_values() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2400})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":4,"shadows":false, + "lights":[{"direction":[2.0,-4.0,8.0],"color":[0.2,0.4,0.6],"intensity":3.0}], + "punctual_lights":[{"position_mm":[10.0,20.0,30.0],"color":[1.0,0.5,0.25],"intensity":4.0, + "reference_distance_mm":100.0,"minimum_distance_mm":0.01, + "cone":{"emitted_axis":[0.0,0.0,-2.0],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.3}}], + "area_lights":[{"center_mm":[0.0,0.0,100.0],"edge_u_mm":[20.0,0.0,0.0],"edge_v_mm":[0.0,-30.0,0.0],"color":[0.3,0.5,0.7],"intensity":5.0}], + "area_samples":16,"seed":9123,"environment":{"color":[0.0,0.0,0.0],"intensity":2.0} + })) + .unwrap(); + let mut expected = RenderSetup { camera: h.app.cam, exposure_ev: 1.5, job: Some(RenderJob::CpuRaytrace { options }), ..Default::default() }; + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + h.app.render_workspace.view.name = "CPU numeric".into(); + setups::load(&mut h.app); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + h.app.run("view.render_select", json!({"kind":"light","id":"directional:0"})).unwrap(); + h.frames(3); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0, "the UI has one exposure authority"); + h.app.render_workspace.view.draft.background = [2, 4, 8]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + expected.background = [2, 4, 8]; + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(json!(expected)["job"]["options"].get("exposure_ev").is_none()); + for value in [json!({}), json!({"lights":[],"punctual_lights":[],"area_lights":[],"environment":{"color":[0.0,0.0,0.0],"intensity":0.0}})] { + let options: CpuJob = serde_json::from_value(value).unwrap(); + expected.job = Some(RenderJob::CpuRaytrace { options }); + h.app.run("render.settings.set", json!({"name":"CPU numeric","set":expected})).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + } +} + +#[test] +fn cpu_progressive_controls_resize_only_on_request_and_save_reload_without_a_host() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.raytrace.primary_samples = 16; + h.app.render_workspace.view.draft.width = 1024; + h.app.render_workspace.view.draft.height = 1024; + h.frames(3); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-progressive"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.raytrace.primary_samples, 1); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions::default())); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: u32::MAX }); + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.name = "Progressive CPU".into(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(image_request(&h.app).is_err()); + assert!(setups::save(&mut h.app).is_err()); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1024, 1024)); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let resize = format!("{} 512 × 512", h.app.tr("render.image_use_largest")); + assert!(h.widget(&resize).is_some(), "the proposed dimensions must be visible before accepting them"); + h.step(&json!({"widget":resize})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (512, 512)); + let expected = setups::snapshot(&h.app).unwrap(); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + assert!(image_request(&h.app).unwrap().get("progressive").is_none(), "CPU sampling must not select the GPU executor"); + h.step(&json!({"widget":h.app.tr("render.save_setup")})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Progressive CPU"], expected); + h.step(&json!({"click":{"handle":"render:cpu-sampling"}})).unwrap(); + h.step(&json!({"click":{"handle":"render:cpu-fixed"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none()); + assert!(h.app.render_workspace.view.dirty); + h.step(&json!({"widget":h.app.tr("render.reload_settings")})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + h.app.render_workspace.view.name = "Progressive CPU copy".into(); + setups::save(&mut h.app).unwrap(); + let reopened = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap(); + h.app.session = Session::new(reopened); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(h.app.render_workspace.view.raytrace.exposure_ev, 0.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 1.25); +} + +#[test] +fn cpu_progressive_setup_preserves_hidden_values_empty_lists_and_one_exposure() { + use solidcraft_engine::doc::render_settings::{CpuJob, RenderJob}; + let mut h = Harness::new(); + h.app.session.set_render_job_host(None).unwrap(); + let options: CpuJob = serde_json::from_value(json!({ + "primary_samples":1,"progressive":{"samples_per_pixel":7,"seed":321},"preset":null, + "lights":[],"punctual_lights":null,"area_lights":[],"area_samples":16,"seed":9123, + "shadows":false,"environment":{"color":[0.0,0.0,0.0],"intensity":0.0} + })) + .unwrap(); + let expected = RenderSetup { + camera: h.app.cam, + width: 32, + height: 16, + exposure_ev: -1.5, + job: Some(RenderJob::CpuRaytrace { options }), + ..Default::default() + }; + h.app.run("render.settings.set", json!({"name":"Progressive hidden","set":expected})).unwrap(); + h.app.render_workspace.view.name = "Progressive hidden".into(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + assert_eq!(image_request(&h.app).unwrap()["settings"]["job"]["method"], "gpu_path"); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().seed = 654; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + let undo = h.app.session.undo.len(); + setups::save(&mut h.app).unwrap(); + assert_eq!(h.app.session.undo.len(), undo, "a no-op Save must preserve all nonedited intent"); +} + +#[test] +fn setup_save_refuses_nonportable_state_atomically_and_tracks_invalid_legacy_edits() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Target"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + setups::load(&mut h.app); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + setups::save(&mut h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.hdr = hdr::Input::FilePending { path: "must-not-be-read.hdr".into() }; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.hdr_inspect_required"))); + h.app.render_workspace.view.studio.environment = studio::Environment::None; + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.render_workspace.view.materials.enabled = false; + assert!(setups::save(&mut h.app).is_err(), "disabled assignments must not be silently lost either"); + h.app.render_workspace.view.materials.bindings.clear(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.app.run("render.settings.set", json!({"name":"Legacy","set":{"job":null,"environment_rotation":0.25,"environment_intensity":2.0}})).unwrap(); + h.app.render_workspace.view.name = "Legacy".into(); + setups::load(&mut h.app); + assert!(!h.app.render_workspace.view.dirty); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.app.render_workspace.view.draft.background = [1, 3, 5]; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty, "invalid saved intent still needs complete dirty tracking"); + assert!(setups::save(&mut h.app).unwrap_err().contains(h.app.tr("render.setup_legacy_environment"))); + assert_eq!(h.app.render_workspace.view.draft.environment_rotation, 0.25); + assert_eq!(h.app.render_workspace.view.draft.environment_intensity, 2.0); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); +} + +fn original_hdr_bytes(value: u8, declared_primaries: bool) -> Vec { + let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n".to_vec(); + if declared_primaries { + bytes.extend_from_slice(b"PRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n"); + } + bytes.extend_from_slice(b"\n-Y 1 +X 2\n"); + bytes.extend_from_slice(&[value, 128, 128, 129, 128, value, 128, 129]); + bytes +} + +/// A verified selector for pure request tests. No file exists or is read by the builder. +fn captured_hdr_input(path: &str) -> hdr::Input { + let bytes = original_hdr_bytes(128, true); + hdr::Input::FileCaptured { + path: path.into(), + metadata: hdr::Metadata { + sha256: solidcraft_engine::doc::render_resources::HdrId::of(&bytes), + width: 2, + height: 1, + encoded_bytes: bytes.len() as u64, + primaries: Some(solidcraft_engine::doc::render_resources::SRGB_D65_PRIMARIES), + }, + } +} + +#[test] +fn hdr_ui_save_embeds_once_without_a_host_and_reload_never_reopens_the_source_path() { + use solidcraft_engine::doc::render_settings::RenderJob; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"HDR target","length":10,"width":20,"height":5})).unwrap(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + let path = h.dir.join("original-embedded.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + let resource = solidcraft_engine::doc::render_resources::HdrId::of(&bytes); + let save = h.app.tr("render.save_setup").to_string(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.render_workspace.view.name = "HDR GPU".into(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.studio.rotation_rad = 1234.567890123; + h.app.render_workspace.view.studio.intensity = 1.75; + h.app.render_workspace.view.samples = 37; + let before = (h.app.session.revision, h.app.session.undo.len()); + hdr::inspect(&mut h.app, hdr::Target::Gpu, path.to_string_lossy().into_owned()).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert!(h.app.session.doc.render.resources.is_empty()); + let unsaved = image_request(&h.app).unwrap(); + assert_eq!(unsaved["environment"]["expected_sha256"], json!(resource)); + h.frames(3); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), before.1 + 1); + assert_eq!(h.app.render_workspace.view.studio.hdr, hdr::Input::EmbeddedResource { resource }); + assert_eq!(h.app.session.doc.render.resources.len(), 1); + let gpu = h.app.session.doc.render.setups.get("HDR GPU").unwrap().clone(); + assert!(matches!(&gpu.job, Some(RenderJob::GpuPath { options, .. }) if options.hdr.unwrap().resource == resource && options.samples == 37)); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":gpu})); + assert!(!h.app.render_workspace.view.dirty); + + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "HDR CPU".into(); + h.app.render_workspace.view.raytrace.progressive = Some(solidcraft_engine::render::job::CpuProgressiveOptions { samples_per_pixel: 7, seed: 84 }); + h.app.render_workspace.view.draft.exposure_ev = 1.75; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.rotation_rad = -1234.567890123; + h.app.render_workspace.view.cpu.intensity = 2.5; + h.app.render_workspace.view.cpu.samples = 64; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let undo = h.app.session.undo.len(); + h.frames(2); + h.step(&json!({"widget":save})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.render.resources.len(), 1, "both setups share one source payload"); + assert_eq!(h.app.session.doc.render.resources.total_bytes(), bytes.len()); + let cpu = h.app.session.doc.render.setups.get("HDR CPU").unwrap().clone(); + assert!(matches!(&cpu.job, Some(RenderJob::CpuRaytrace { options }) + if options.hdr.unwrap().samples == 64 && options.progressive.unwrap().samples_per_pixel == 7 && options.progressive.unwrap().seed == 84)); + let encoded = h.app.session.doc.to_json(); + assert!(!encoded.contains("original-embedded.hdr"), "the document never stores the source path"); + std::fs::remove_file(&path).unwrap(); + + for (name, expected, target) in [("HDR GPU", gpu, hdr::Target::Gpu), ("HDR CPU", cpu, hdr::Target::Cpu)] { + let loaded = solidcraft_engine::doc::Document::from_json(&encoded).unwrap(); + h.app.session = Session::new(loaded); + h.app.render_workspace.view.name = name.into(); + setups::load(&mut h.app); + let camera = expected.camera; + h.app.cam = camera; + assert_eq!(hdr::input(&h.app, target), &hdr::Input::EmbeddedResource { resource }); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert_eq!(image_request(&h.app).unwrap(), json!({"settings":expected})); + let before = (h.app.session.revision, h.app.session.undo.len()); + let section = if target == hdr::Target::Cpu { "render.cpu_environment" } else { "render.studio_environment" }; + h.frames(2); + if target == hdr::Target::Gpu { + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr("render.image_advanced"))}})).unwrap(); + } + h.step(&json!({"click":{"handle":format!("dialog:section:{}", h.app.tr(section))}})).unwrap(); + h.frames(2); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected, "displaying degrees must preserve saved radians"); + setups::save(&mut h.app).unwrap(); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), before); + assert_eq!(h.app.cam, camera); + } +} + +#[test] +fn changed_hdr_bytes_reject_save_atomically_and_check_start_keep_the_expected_digest() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Pinned HDR".into(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + let path = h.dir.join("changing.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let input = h.app.render_workspace.view.cpu.hdr.clone(); + let request = image_request(&h.app).unwrap(); + let doc = h.app.session.doc.clone(); + let draft = h.app.render_workspace.view.draft.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + std::fs::write(&path, original_hdr_bytes(64, true)).unwrap(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), before); + assert_eq!(h.app.render_workspace.view.cpu.hdr, input); + assert_eq!(h.app.render_workspace.view.draft, draft); + assert_eq!(image_request(&h.app).unwrap(), request, "both buttons keep the verified digest, never silently accept new bytes"); + assert!(h.app.session.doc.render.resources.is_empty()); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert_ne!(h.app.render_workspace.view.cpu.hdr.resource(), input.resource()); + setups::save(&mut h.app).unwrap(); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + assert_eq!(h.app.session.doc.render.resources.len(), 1); +} + +#[test] +fn hdr_picker_cancel_and_late_setup_method_or_input_answers_preserve_the_selection() { + use crate::picker_test_support::{Slot, open}; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + for change in ["cancel", "setup", "method", "input"] { + let mut h = Harness::new(); + h.app.render_workspace.view.method = if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("original.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("original.hdr"); + let slot: Slot = Default::default(); + open(&mut h.app, &slot); + hdr::pick(&mut h.app, target); + let ctx = crate::fonts::test_context(); + crate::file_picker::tick(&mut h.app, &ctx); + match change { + "setup" => h.app.render_workspace.view.name = "another setup".into(), + "method" => h.app.render_workspace.view.method = ImageMethod::Raster, + "input" => { + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("newer.hdr"); + h.app.render_workspace.view.studio.hdr = captured_hdr_input("newer.hdr"); + } + _ => {} + } + let before = hdr::input(&h.app, target).clone(); + let doc = h.app.session.doc.clone(); + let status = h.app.status.clone(); + *slot.borrow_mut() = Some(if change == "cancel" { None } else { Some("never-read-late.hdr".into()) }); + crate::file_picker::tick(&mut h.app, &ctx); + assert_eq!(hdr::input(&h.app, target), &before, "{target:?}: {change}"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status, status, "the stale path must be discarded before trying to inspect it"); + } + } +} + +#[test] +fn embedded_hdr_runtime_requests_preserve_temporary_bindings_without_serializing_them() { + use solidcraft_engine::render::job::ReflectionMode; + for target in [hdr::Target::Cpu, hdr::Target::Gpu] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"body_name":"Target","length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, if target == hdr::Target::Cpu { ImageMethod::CpuRaytrace } else { ImageMethod::GpuRaytrace }); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.studio.environment = studio::Environment::Hdr; + let path = h.dir.join("bindings.hdr"); + std::fs::write(&path, original_hdr_bytes(128, true)).unwrap(); + hdr::inspect(&mut h.app, target, path.to_string_lossy().into_owned()).unwrap(); + setups::save(&mut h.app).unwrap(); + let resource = hdr::input(&h.app, target).resource().unwrap(); + std::fs::remove_file(&path).unwrap(); + if target == hdr::Target::Cpu { + cpu::set_reflection(&mut h.app, "Target", Some(ReflectionMode::Mirror)).unwrap(); + } else { + let target: materials::Target = serde_json::from_value(h.app.run("render.scene", json!({})).unwrap()["bodies"][0].clone()).unwrap(); + let binding = materials::Binding::new(target, &h.app); + h.app.render_workspace.view.materials.bindings.push(binding); + // Even disabled, this assignment must not be lost on Save. It still + // selects the runtime path and exercises the embedded HDR selector. + h.app.render_workspace.view.materials.enabled = false; + } + let params = image_request(&h.app).unwrap(); + assert_eq!(params["environment"]["resource"], json!(resource)); + assert!(params["environment"].get("path").is_none()); + assert!(params["environment"].get("expected_sha256").is_none()); + if target == hdr::Target::Cpu { + assert!(params["environment"].get("kind").is_none()); + assert_eq!(params["raytrace"]["reflections"]["bodies"][0]["body"], "Target"); + } else { + assert_eq!(params["environment"]["kind"], "embedded_hdr"); + } + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assert!(setups::save(&mut h.app).is_err()); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(image_request(&h.app).unwrap(), params); + } +} + +#[test] +fn cpu_resource_profile_edits_preserve_resolution_samples_and_saved_intent() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.app.render_workspace.view.name = "Studio output".into(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Studio; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 82 }); + h.frames(3); + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + + h.step(&json!({"click":{"handle":"render.cpu_budget_compact"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (3840, 2160)); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 128); + assert!(setups::snapshot(&h.app).is_err()); + assert!(h.app.render_workspace.view.dirty); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); +} + +#[test] +fn large_image_display_uses_captured_profile_and_keeps_export_pixels_unchanged() { + use solidcraft_engine::render::job::{CpuBudget, ImageRequest, RaytraceOptions}; + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { budget: CpuBudget::Studio, ..Default::default() }), + camera: Camera::default(), + width: 8, + height: 8, + background: [0; 3], + transparent_background: false, + environment: None, + textures: None, + }; + let limits = captured_image_limits(&request); + assert_eq!(limits, CpuBudget::Studio.image_limits(false)); + assert_eq!(display_dimensions(7680, 4320, 4096).unwrap(), (4096, 2304)); + assert_eq!(display_dimensions(1920, 1080, 4096).unwrap(), (1920, 1080)); + assert!(display_dimensions(u32::MAX, 1, 0).is_err()); + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(8200, 2, image::Rgba([42, 88, 123, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let encoded = png.into_inner(); + let before = encoded.clone(); + assert!(decode_image(&encoded, 8200, 2).is_err(), "legacy default remains compact"); + let display = decode_render_image(&encoded, 8200, 2, CpuBudget::Workstation.image_limits(false), 1024).unwrap(); + assert!(display.size[0] <= 1024 && display.size[1] >= 1); + assert_eq!(encoded, before, "the retained image is not rewritten for its display cache"); + assert!(decode_render_image(&encoded, 8199, 2, CpuBudget::Workstation.image_limits(false), 1024).is_err()); +} + +#[test] +fn setup_actions_and_return_design_stay_visible_with_long_render_controls() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + h.frames(3); + for key in ["render.save_setup", "render.reload_settings", "render.return_design"] { + let label = h.app.tr(key).to_string(); + assert!(h.widget(&label).is_some(), "sticky action {key}"); + } + h.step(&json!({"widget":h.app.tr("render.return_design")})).unwrap(); + assert!(!active(&h.app)); +} + +#[test] +fn dirty_indication_preserves_reload_and_resource_picker_hit_targets() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2600})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::All; + select_image_method(&mut h.app, ImageMethod::CpuRaytrace); + setups::save(&mut h.app).unwrap(); + setups::load(&mut h.app); + h.frames(3); + let reload = h.app.tr("render.reload_settings").to_string(); + let clean_reload = h.widget(&reload).unwrap(); + let clean_picker = crate::scenario::rect_of("render:cpu-budget").unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + setups::refresh_dirty(&mut h.app); + assert!(h.app.render_workspace.view.dirty); + h.frames(3); + assert_eq!(h.widget(&reload).unwrap(), clean_reload, "dirty text must not move Reload"); + assert_eq!(crate::scenario::rect_of("render:cpu-budget").unwrap(), clean_picker, "dirty text must not move the CPU resource picker"); + h.step(&json!({"widget":reload})).unwrap(); + if h.app.render_workspace.view.dirty { + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + } + assert!(!h.app.render_workspace.view.dirty); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, 0.0); +} + +#[test] +fn product_preview_exact_payload_preserves_mixed_surfaces_and_refuses_overflow() { + let mut session = Session::default(); + for (name, x) in [("Paint", 0), ("Legacy", 20), ("Glass", 40)] { + session.execute("solid.box", &json!({"base":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + session + .execute("appearance.assign", &json!({"bodies":["Paint"],"color":"#c07030","pbr":{"metallic":0,"roughness":0.4,"dielectric_ior":1.5}})) + .unwrap(); + session.execute("appearance.assign", &json!({"bodies":["Glass"],"color":"#336699","opacity":0.4})).unwrap(); + let original = session.doc.to_json(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + let (_, gpu) = gpu_scene(&scene).unwrap(); + assert_eq!((plan.pbr, plan.tris, plan.glass), (gpu.pbr.len(), gpu.tris.len(), gpu.glass.len())); + assert!(plan.pbr > 0 && plan.tris > 0 && plan.glass > 0); + assert_eq!(plan.source_triangles, scene.meshes.iter().map(|b| b.mesh.triangles.len()).sum::()); + assert!(preview_upload_plan(&scene, plan.bytes().unwrap() - 1).is_err()); + assert!(PreviewUploadPlan::default().add(true, false, usize::MAX, MAX_GEOMETRY_BYTES).is_err()); + assert_eq!(session.doc.to_json(), original); + let mut invalid = scene.clone(); + let source = invalid.meshes[0].mesh.clone(); + Arc::make_mut(&mut invalid.meshes[0].mesh).triangles[0][0] = u32::MAX; + assert!(gpu_scene(&invalid).is_err()); + assert!(gpu_scene(&scene).is_ok()); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &source)); +} + +#[cfg(all(not(target_arch = "wasm32"), target_pointer_width = "64"))] +#[test] +fn full_detail_preview_source_can_exceed_legacy_128_mib_without_mesh_reduction() { + use solidcraft_engine::geom::{Mesh, Vec3}; + use solidcraft_engine::render::{ProductMesh, surface::OpaqueSurface}; + // One immutable original triangle repeated in the index list; this tests + // payload admission only. Actual SELENE upload is separate native evidence. + let count = (128 * 1024 * 1024) / (3 * crate::gpu::PBR_SIZE) + 1; + let mesh = Arc::new(Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + normals: vec![Vec3::Z; 3], + triangles: vec![[0, 1, 2]; count], + ..Default::default() + }); + let body = ProductMesh { + name: "Original admission fixture".into(), + mesh: mesh.clone(), + color: [200, 100, 50], + opacity: 1.0, + surface: Some(OpaqueSurface::new(Vec3::new(0.4, 0.2, 0.1), 0.0, 0.4, 1.5).unwrap()), + transmission: None, + faces: Vec::new(), + }; + let scene = ProductScene { meshes: vec![body], bounds: mesh.bounds() }; + assert!(preview_upload_plan(&scene, 128 * 1024 * 1024).is_err()); + let plan = preview_upload_plan(&scene, MAX_GEOMETRY_BYTES).unwrap(); + assert_eq!(plan.source_triangles, count); + assert_eq!(plan.bytes().unwrap(), count * 3 * crate::gpu::PBR_SIZE); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &mesh)); + let mut maximum = PreviewUploadPlan::default(); + assert!(maximum.add(true, false, MAX_GEOMETRY_BYTES / (3 * crate::gpu::PBR_SIZE) + 1, MAX_GEOMETRY_BYTES).is_err()); +} + +#[test] +fn refused_product_capture_is_cached_until_identity_changes_or_explicit_retry() { + let mut h = Harness::new(); + let calls = std::cell::Cell::new(0); + let signature = (7, 123, 99, MAX_GEOMETRY_BYTES as u64); + for _ in 0..8 { + assert_eq!( + h.app + .render_workspace + .prepare_preview(signature, || { + calls.set(calls.get() + 1); + Err("original bounded refusal".into()) + }) + .unwrap_err(), + "original bounded refusal" + ); + } + assert_eq!(calls.get(), 1, "same refused source is not rebuilt every frame"); + assert!(h.app.render_workspace.scene.is_none() && h.app.render_workspace.key.is_none()); + assert!(h.app.render_workspace.slot.lock().unwrap().is_none()); + assert!( + h.app + .render_workspace + .prepare_preview((8, 123, 99, MAX_GEOMETRY_BYTES as u64), || { + calls.set(calls.get() + 1); + Err("new revision".into()) + }) + .is_err() + ); + assert_eq!(calls.get(), 2); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.scene_signature.is_none() && h.app.render_workspace.scene_error.is_none()); + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + h.app.render_workspace.prepare_preview(signature, || solidcraft_engine::product_scene::extract(&session).map_err(|e| e.to_string())).unwrap(); + assert!(h.app.render_workspace.scene_error.is_none()); + assert!(h.app.render_workspace.preview_upload_bytes.unwrap() > 0); + assert!(h.app.render_workspace.key.is_some() && h.app.render_workspace.scene.is_some()); +} + +#[test] +fn product_preview_error_uses_shared_wrapped_surface_and_explicit_retry_target() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1280,"height":800})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rect = egui::Rect::from_min_size(egui::pos2(260.0, 200.0), egui::vec2(550.0, 360.0)); + let message = "The original captured product geometry exceeds its bounded preview admission. The renderer must preserve all exact body identities and cannot silently simplify or drop geometry to paint this view."; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), ..Default::default() }, + |ui| preview_error(&mut h.app, ui, rect, message), + ); + output.textures_delta.clear(); + let note = crate::scenario::rect_of("dialog:report:render.preview_failure").unwrap(); + let retry = crate::scenario::rect_of("render:preview-retry").unwrap(); + assert!(rect.contains_rect(note) && rect.contains_rect(retry)); + assert!(note.height() > Tokens::get().font_body, "the detailed failure wraps instead of escaping the viewport"); + assert!(crate::theme::contrast_ratio(Tokens::get().form_error, Tokens::get().form_error_fill) >= 3.0); +} + +#[test] +fn finishing_backdrop_and_raw_retention_save_reload_without_a_gpu_or_hidden_transport_edits() { + use solidcraft_engine::render::job::finishing::{Backdrop, BackdropMode, Finishing}; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2200})); + enter(&mut h.app, true).unwrap(); + h.app.session.set_render_job_host(None).unwrap(); + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.render_workspace.view.name = "Linear studio".into(); + h.app.render_workspace.view.studio.finishing = + Finishing { rgb_gain: [1.3, 0.8, 0.9], saturation: 0.4, contrast: 1.2, vignette: 0.3, ..Default::default() }; + h.app.render_workspace.view.studio.backdrop_enabled = true; + h.app.render_workspace.view.studio.backdrop = Backdrop { mode: BackdropMode::Radial, center: [0.25, 0.7], ..Default::default() }; + h.app.render_workspace.view.studio.linear_exr = true; + let expected = setups::snapshot(&h.app).unwrap(); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.studio = studio::View::default(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), expected); + assert!(!h.app.render_workspace.view.dirty); + assert!(!studio::linear_export_available(&h.app)); + let request = image_request(&h.app).unwrap(); + assert_eq!(request["settings"]["job"]["options"]["linear_exr"], true); + assert_eq!(request["settings"]["job"]["options"]["finishing"]["rgb_gain"], json!([1.3, 0.8, 0.9])); + assert!(image_params(&h.app).is_err(), "offline editing is not a claim of executable GPU capabilities"); + h.app.render_workspace.view.transparent = true; + assert!(setups::snapshot(&h.app).is_err(), "gradient cannot silently disappear behind alpha mode"); + h.app.render_workspace.view.transparent = false; + let before = h.app.session.doc.to_json(); + h.frames(3); + h.app.run("view.render_select", json!({"kind":"effects"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:post-reset"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.studio.finishing, Finishing::default()); + assert!(h.app.render_workspace.view.studio.linear_exr); + assert!(h.app.render_workspace.view.studio.backdrop_enabled); + assert!(h.app.render_workspace.view.dirty); + assert_ne!(h.app.session.doc.to_json(), before, "Effects saves its job patch through the shared editor"); + let reset = setups::snapshot(&h.app).unwrap(); + setups::load(&mut h.app); + assert_eq!(setups::snapshot(&h.app).unwrap(), reset); +} + +#[test] +fn missing_linear_master_is_never_reconstructed_from_a_finished_png() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + enter(&mut h.app, true).unwrap(); + let id = completed_preview(&mut h, [21, 37, 55]); + let bytes = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.completed = Some(id); + h.app.render_workspace.view.studio.export_exr = true; + assert!(!studio::linear_export_available(&h.app)); + let temp = std::env::temp_dir().join(format!("solidcraft-missing-linear-{}.exr", std::process::id())); + assert!(h.app.session.execute("render.export", &json!({"job":id,"path":temp,"format":"exr"})).is_err()); + assert!(!temp.exists()); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), bytes); +} + +#[test] +fn render_workspace_stage_commands_keep_registered_actions_without_a_ribbon() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + assert!(crate::workspace::visible_tabs(&h.app).is_empty()); + for command in solidcraft_engine::command_specs() + .into_iter() + .filter(|c| c.id.starts_with("render.") || c.tab.starts_with("RENDER") || c.id == "view.shots_strip") + { + assert!(solidcraft_engine::find_command(command.id).is_some()); + assert!(crate::workspace::destination(command).is_none(), "{} has a ribbon destination", command.id); + } + for tab in ["RENDER", "RENDER APPEARANCE", "RENDER SCENE", "RENDER CAMERA"] { + assert!(crate::workspace::panels(tab).is_empty()); + } + h.frames(3); + assert!(crate::scenario::rect_of("ribbon:card").is_none()); + assert!(crate::scenario::rect_of("tab:RENDER").is_none()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); +} + +#[test] +fn render_workspace_stage_chips_dispatch_without_mutations_and_remember_each_document() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for stage in Stage::ALL { + h.frames(3); + h.step(&json!({"click":{"handle":format!("render:stage:{}",stage.key())}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.stage, stage); + assert_eq!(h.app.render_workspace.view.inspector.page, stage.page()); + assert_eq!(crate::scenario::rect_of("render:pick").is_some(), stage == Stage::Look); + assert_eq!(crate::scenario::rect_of("render:preview_note").is_some(), stage == Stage::Look); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + // Registered editor navigation remains available independently of the stage. + for command in ["render.status", "render.backends"] { + h.app.start(command); + h.frames(2); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Diagnostics); + } + } + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Look); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Frame); + crate::documents::switch(&mut h.app, 1); + enter(&mut h.app, true).unwrap(); + assert_eq!(h.app.render_workspace.view.stage, Stage::Light); +} + +#[test] +fn render_workspace_stage_shell_degrades_without_overlap_at_small_window_sizes() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.ui.layout = mode; + for (width, height) in [ + (1440, 900), + (1400, 900), + (1100, 700), + (900, 700), + (800, 600), + (700, 600), + (640, 480), + (320, 240), + (240, 160), + (120, 80), + (32, 32), + (1, 1), + ] { + h.call("ui.resize", json!({"width":width,"height":height})); + for stage in Stage::ALL { + h.app.run("view.render_stage", json!({"stage":stage.key()})).unwrap(); + h.frames(3); + let bar = crate::scenario::rect_of("render:stage_bar").unwrap(); + let workspace = crate::scenario::rect_of("ribbon:workspace").unwrap(); + assert!(bar.is_finite() && workspace.is_finite()); + assert_eq!(bar.top(), workspace.top()); + assert_eq!(bar.height(), workspace.height()); + assert!(!bar.intersect(workspace).is_positive()); + if width >= 1100 { + assert_eq!(bar.height(), 88.0); + assert_eq!(workspace.width(), 104.0); + assert_eq!(bar.left() - workspace.right(), 8.0); + let header = crate::scenario::rect_of("render:stage_header").unwrap(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert_eq!(header.height(), 36.0); + assert_eq!(tools.height(), 52.0); + assert_eq!(header.bottom(), tools.top()); + assert_eq!(header.top(), bar.top()); + assert_eq!(tools.bottom(), bar.bottom()); + } + let docks: Vec<_> = + ["render:browser", "render:inspector"].iter().filter_map(|id| h.app.shell.workspace_panels.get(id).map(|(r, _)| *r)).collect(); + if let [browser, inspector] = docks.as_slice() { + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!(browser.bottom() < inspector.bottom()); + assert!(!browser.intersect(*inspector).is_positive()); + if width >= 800 { + let compact = crate::render_ui::compact(&h.app, width as f32); + assert_eq!(browser.width(), if compact { crate::frame::DIALOG_MIN_W } else { 266.0 }); + assert_eq!(inspector.width(), if compact { crate::frame::DIALOG_MIN_W } else { 305.0 }); + assert_eq!(browser.top() - bar.bottom(), 8.0); + let (strip, _) = h.app.shell.workspace_panels.get("render:shots_strip").unwrap(); + let library = h.app.shell.workspace_panels["render:appearances"].0; + assert_eq!(strip.top() - library.bottom(), 8.0); + assert_eq!(library.top() - browser.bottom(), 8.0); + assert_eq!(strip.height(), 48.0); + } + } + if (640..800).contains(&width) { + assert!(crate::scenario::rect_of("render:browser:show").is_some()); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + if width >= 700 { + for dock in &docks { + assert!(!dock.x_range().contains(h.app.viewport.rect.unwrap().center().x), "{width}: {dock:?}"); + } + } + let mut docks = docks; + if let Some((panel, _)) = h.app.shell.workspace_panels.get("render:appearances") { + for dock in &docks { + assert!(!panel.intersect(*dock).is_positive()); + } + docks.push(*panel); + } + for dock in docks { + assert!(!dock.intersect(bar).is_positive(), "{width}×{height}: {dock:?} {bar:?}"); + if let Some((strip, _)) = h.app.shell.workspace_panels.get("render:shots_strip") { + assert!(!dock.intersect(*strip).is_positive(), "{width}×{height}: {dock:?} {strip:?}"); + } + } + } + } + } +} + +#[test] +fn render_workspace_focus_restores_docks_without_design_history_or_camera_changes() { + for (side, folded, shots) in [("left", false, true), ("right", true, false)] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 350.0; + h.app.preferences.render_inspector_width = 390.0; + h.app.preferences.render_shots_strip = shots; + h.app.preferences.browser_collapsed = folded; + h.app.shell.render_browser_open = folded; + h.frames(3); + let dock_preferences = h.app.prefs(); + let docks = h.app.shell.workspace_panels.clone(); + let camera = (h.app.cam, h.app.session.camera); + let document = h.app.session.doc.clone(); + let state = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let before = h.app.viewport.layout.as_ref().unwrap().content; + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + assert!(crate::render_ui::focused(&h.app)); + crate::shell::register_panel(&mut h.app, "render:stage_panel", Some(before), Some(crate::ui_kit::Edge::Left)); + assert!(!h.app.shell.workspace_panels.contains_key("render:stage_panel")); + for id in ["render:browser", "render:appearances", "render:inspector", "render:shots_strip", "render:shots:show"] { + assert!(!h.app.shell.workspace_panels.contains_key(id)); + assert!(crate::scenario::rect_of(id).is_none()); + } + for id in ["render:focus:exit", "render:stage_bar", "ribbon:workspace"] { + assert!(crate::scenario::rect_of(id).is_some(), "{id}"); + } + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(layout.content.width() > before.width()); + assert!(layout.axis_view.is_positive() && layout.navigation.is_positive()); + assert_eq!(h.app.prefs(), dock_preferences); + h.step(&json!({"click":{"handle":"render:focus:exit"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.render_focus); + assert_eq!(h.app.shell.workspace_panels.len(), docks.len()); + for (id, (rect, edge)) in docks { + let (restored_rect, restored_edge) = h.app.shell.workspace_panels.get(id).unwrap(); + assert_eq!(*restored_rect, rect); + assert_eq!(restored_edge.as_ref().map(std::mem::discriminant), edge.as_ref().map(std::mem::discriminant)); + } + assert_eq!(h.app.prefs(), dock_preferences); + assert_eq!(h.app.preferences.browser_collapsed, folded); + assert_eq!(h.app.shell.render_browser_open, folded); + assert_eq!((h.app.cam, h.app.session.camera), camera); + assert!(Arc::ptr_eq(&h.app.session.doc, &document)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), state); + assert!(!Harness::new().app.shell.render_focus); + } +} + +#[test] +fn render_workspace_focus_tab_only_toggles_render_without_text_focus() { + let mut h = Harness::new(); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(h.app.shell.render_focus); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); + h.frames(3); + h.step(&json!({"click":{"handle":"render:library-search"}})).unwrap(); + assert!(h.ctx.egui_wants_keyboard_input()); + h.step(&json!({"key":"Tab"})).unwrap(); + assert!(!h.app.shell.render_focus); +} + +#[test] +fn render_workspace_compact_browser_card_and_focus_preserve_remembered_widths() { + for side in ["left", "right"] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_side = side.into(); + h.app.preferences.render_inspector_side = if side == "left" { "right" } else { "left" }.into(); + h.app.preferences.render_browser_width = 320.0; + h.app.preferences.render_inspector_width = 360.0; + h.frames(3); + for width in [1100, 900, 700] { + h.call("ui.resize", json!({"width":width,"height":700})); + h.frames(3); + if width == 700 { + h.step(&json!({"click":{"handle":"render:browser:show"}})).unwrap(); + h.frames(3); + let (browser, reservation) = h.app.shell.workspace_panels["render:browser"]; + let (inspector, _) = h.app.shell.workspace_panels["render:inspector"]; + assert!(reservation.is_none(), "narrow Browser overlays the canvas"); + assert!(!browser.intersect(inspector).is_positive()); + h.app.run("view.render_focus", json!({"on":true})).unwrap(); + h.frames(3); + h.app.run("view.render_focus", json!({"on":false})).unwrap(); + h.frames(3); + assert!(h.app.shell.render_browser_open); + assert!(h.app.shell.workspace_panels.contains_key("render:browser")); + h.step(&json!({"click":{"handle":"render:browser:hide"}})).unwrap(); + h.frames(3); + assert!(!h.app.shell.workspace_panels.contains_key("render:browser")); + } + assert_eq!(h.app.preferences.render_browser_width, 320.0); + assert_eq!(h.app.preferences.render_inspector_width, 360.0); + } + h.call("ui.resize", json!({"width":1400,"height":900})); + h.frames(3); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0.width(), 320.0); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), 360.0); + } +} + +#[test] +fn render_workspace_focus_messages_have_five_complete_locales() { + let keys = [ + "cmd.view.render_focus", + "cmd.view.render_browser", + "render.exit_focus", + "render.fold_browser", + "render.spot_cone", + "render.emitted_axis", + "render.inner_half_angle", + "render.outer_half_angle", + "render.layer_off_suffix", + "render.tone_reinhard", + "render.tone_aces_fitted", + "render.size_hd", + "render.size_full_hd", + "render.size_4k_uhd", + "render.result_actual_size", + "render.property_unknown", + "render.property_fallback", + "render.property_source", + "render.property_qualifier", + "render.property_conditions", + "render.property_uncertainty", + "render.error_setup_panicked", + "render.error_setup_worker", + "render.error_setup_stopped", + "render.error_gpu_samples", + "render.error_preview_device", + "render.error_finish_operation", + "render.error_no_completed_image", + "render.error_provisional_identity", + "render.error_checkpoint_dimensions", + "render.error_display_dimensions", + "render.error_display_fit", + "render.error_display_width", + "render.error_display_height", + "render.error_image_profile", + "render.error_decode_budget", + "render.error_image_dimensions", + "render.error_upload_slot", + "render.error_export_document", + "render.error_geometry_size", + "render.error_vertex_envelope", + "render.error_body_bound", + "render.error_triangle_count", + "render.error_triangle_bound", + "render.error_face_cap", + "render.error_opacity", + "render.error_duplicate_face", + "render.error_pbr_opacity", + "render.error_vertex_allocation", + "render.error_product_triangle", + "render.error_surface_normals", + "render.error_vertex_packing", + "render.error_gpu_preview", + "render.error_fixed_preview", + "render.error_finish_gesture", + "render.error_no_scene", + "render.error_no_geometry", + "render.error_visible_solid", + "render.error_area_samples", + "render.error_quality_method", + "render.error_quality_projection", + "render.error_denoise_setting", + "render.error_quality_bounds", + "render.error_library_reply", + "render.error_source_preview", + "render.error_glass_recipe", + "render.error_physical_glass", + "render.error_scene_bodies", + "render.error_scene_body_limit", + "render.error_scene_identity", + "render.error_material_binding", + "render.error_surface_reply", + "render.error_binding_allocation", + "render.error_job_identity", + "render.error_regrade_identity", + "render.error_job_action", + "render.error_interactive_command", + ]; + for (language, source) in [ + ("en", include_str!(concat!(env!("OUT_DIR"), "/locales/en.json"))), + ("ja", include_str!(concat!(env!("OUT_DIR"), "/locales/ja.json"))), + ("zh", include_str!(concat!(env!("OUT_DIR"), "/locales/zh.json"))), + ("de", include_str!(concat!(env!("OUT_DIR"), "/locales/de.json"))), + ("ko", include_str!(concat!(env!("OUT_DIR"), "/locales/ko.json"))), + ] { + let translated: std::collections::BTreeMap = serde_json::from_str(source).unwrap(); + let locale = crate::i18n::Locale::for_language(language); + for key in keys { + let value = translated.get(key).unwrap_or_else(|| panic!("{language}: missing {key}")); + assert!(!value.is_empty()); + assert_eq!(locale.text(key), value); + } + let sentence = locale.format("render.property_source", &[("id", "A"), ("locator", "B")]); + assert!(sentence.contains('A') && sentence.contains('B') && !sentence.contains('{')); + } +} + +#[test] +fn render_workspace_chrome_uses_tokens_instead_of_literal_colours() { + use syn::visit::{self, Visit}; + #[derive(Default)] + struct Colours(Vec); + impl<'ast> Visit<'ast> for Colours { + fn visit_expr_path(&mut self, expr: &'ast syn::ExprPath) { + let names: Vec<_> = expr.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") && names.last().is_some_and(|s| matches!(s.as_str(), "WHITE" | "BLACK" | "GRAY")) { + self.0.push(names.join("::")); + } + visit::visit_expr_path(self, expr); + } + fn visit_expr_call(&mut self, expr: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = expr.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|s| s == "Color32") + && names.last().is_some_and(|s| s.starts_with("from_rgb") || s == "from_gray") + && expr.args.iter().all(|arg| matches!(arg, syn::Expr::Lit(_))) + { + self.0.push(names.join("::")); + } + } + visit::visit_expr_call(self, expr); + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files: Vec<_> = std::fs::read_dir(&root) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|path| { + let name = path.file_name().unwrap().to_string_lossy(); + name.starts_with("render_workspace") && name.ends_with(".rs") && !name.contains("tests") + }) + .collect(); + let mut folders = vec![root.join("render_ui")]; + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else if path.extension().is_some_and(|e| e == "rs") { + files.push(path); + } + } + } + for path in files { + let source = std::fs::read_to_string(&path).unwrap(); + let mut colours = Colours::default(); + colours.visit_file(&syn::parse_file(&source).unwrap()); + assert!(colours.0.is_empty(), "{}: {:?}", path.display(), colours.0); + } +} + +#[test] +fn render_workspace_shots_toggle_persists_and_design_roundtrip_preserves_state() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1000})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Subject".into() }]; + h.app.cam.yaw = 0.71; + h.app.cam.pitch = 0.23; + h.app.cam.roll = 0.17; + let camera = h.app.cam; + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let state = ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed, + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() <= 1.0, "{strip:?}"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.session.doc, document); + assert_eq!( + state, + ( + h.app.session.undo.len(), + h.app.session.redo.len(), + h.app.session.revision, + h.app.ui.show_timeline, + h.app.preferences.timeline_left, + h.app.preferences.timeline_collapsed + ) + ); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_none()); + assert!(crate::scenario::rect_of("render:shots:show").is_some()); + h.step(&json!({"click":{"handle":"render:shots:show"}})).unwrap(); + assert!(h.app.preferences.render_shots_strip); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + assert!(!h.app.preferences.render_shots_strip); + let saved = h.app.prefs(); + let mut next = Harness::new(); + next.app.load_prefs(&saved); + assert!(!next.app.preferences.render_shots_strip); + h.frames(2); + h.app.start("view.shots_strip"); + assert!(h.app.preferences.render_shots_strip); + h.frames(3); + assert!(crate::scenario::rect_of("render:shots_strip").is_some()); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), state.0); +} + +#[test] +fn render_workspace_canvas_controls_and_fit_respect_panels_and_shots_in_both_layouts() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":60,"width":40,"height":30})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.cam.fov = 0.9; + h.app.start("render.camera.fit"); + h.frames(4); + assert_eq!(h.app.cam.fov, 0.9); + let free = crate::shell::content_rect(&h.app, h.app.viewport.rect.unwrap()); + let layout = h.app.viewport.layout.as_ref().unwrap(); + assert!(free.contains_rect(layout.navigation), "{free:?} {layout:?}"); + assert!((layout.navigation.center().x - free.center().x).abs() < 1.0); + assert_product_fits_canvas(&h.app); + } +} + +#[test] +fn render_workspace_old_personal_pins_migrate_once_to_task_tabs() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER/SCENE":["render.settings.get","render.preset.resolve","solid.box"], + "DESIGN/RENDER/LIGHTING":["render.library.studio.apply"], + "DESIGN/RENDER/CAMERA":["render.settings.apply","render.camera.fit"], + "DESIGN/RENDER/IMAGE":["render.export","render.start"], + "DESIGN/RENDER/OUTPUT":["render.preflight"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/SHOTS"], ["render.settings.get", "solid.box"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.preset.resolve", "render.library.studio.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER CAMERA/VIEW"], ["render.settings.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.start", "render.preflight"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +#[test] +fn render_workspace_scene_vocabulary_migrates_previous_shell_pins_once() { + let mut custom = crate::toolbar_custom::ToolbarCustom::default(); + custom.load(&json!({"version":2,"panels":{ + "DESIGN/RENDER LIGHTING/LIGHTING":["render.library.studio.apply","render.lights.solo"], + "DESIGN/RENDER LIGHTING/ENVIRONMENT":["render.library.environment.apply","render.hdr.inspect"], + "DESIGN/RENDER/OUTPUT":["render.preflight","render.quality.prepare"], + "DESIGN/RENDER/RESULTS":["render.export","render.effects.describe"] + }})); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STUDIO"], ["render.library.studio.apply", "render.library.environment.apply"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/LIGHTS"], ["render.lights.solo"]); + assert_eq!(custom.panels["DESIGN/RENDER SCENE/STAGE"], ["render.hdr.inspect"]); + assert_eq!(custom.panels["DESIGN/RENDER/IMAGE"], ["render.quality.prepare", "render.effects.describe"]); + assert_eq!(custom.panels["DESIGN/RENDER/RENDER"], ["render.preflight"]); + assert_eq!(custom.panels["DESIGN/RENDER/RESULT"], ["render.export"]); + let saved = custom.prefs(); + custom.load(&saved); + assert_eq!(custom.prefs(), saved); +} + +fn assert_product_fits_canvas(app: &SolveApp) { + let layout = app.viewport.layout.as_ref().unwrap(); + let free = crate::shell::content_rect(app, layout.viewport); + assert!(free.contains_rect(layout.drawable), "fit region {:?} outside canvas {free:?}", layout.drawable); + let bounds = solidcraft_engine::product_scene::extract(&app.session).unwrap().bounds; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (sx, sy, _) = app + .cam + .to_screen( + solidcraft_engine::geom::Vec3::new(x, y, z), + f64::from(layout.viewport.width()), + f64::from(layout.viewport.height()), + bounds.diagonal().max(10.0), + ) + .unwrap(); + let at = layout.viewport.min + egui::vec2(sx as f32, sy as f32); + assert!(layout.drawable.contains(at), "product corner {at:?} outside {:?}", layout.drawable); + } + } + } +} + +#[test] +fn render_workspace_hosts_float_and_shield_input_in_both_ribbon_layouts() { + for (layout, page) in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] + .into_iter() + .flat_map(|layout| [inspector::Page::Scene, inspector::Page::Appearance].map(|page| (layout, page))) + { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + h.app.run("solid.box", json!({"length":30,"width":20,"height":10})).unwrap(); + h.frames(4); + + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.inspector.page = page; + h.frames(4); + let viewport = h.app.viewport.rect.unwrap(); + let history = crate::timeline::floating_rect(viewport); + let shots = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((shots.height() - 48.0).abs() <= 1.0, "{layout:?}: {shots:?}"); + assert!( + (shots.left() - history.left()).abs() < 1.0 + && (shots.right() - history.right()).abs() < 1.0 + && (shots.bottom() - history.bottom()).abs() < 1.0, + "Shots must reuse History's floating placement: {shots:?} {history:?}" + ); + for key in ["render:inspector", "render:browser", "render:appearances", "render:shots_strip"] { + let (card, _) = h.app.shell.workspace_panels.get(key).unwrap(); + assert!(viewport.contains_rect(*card), "{layout:?} {key}: {card:?} outside {viewport:?}"); + assert!(crate::shell::covered(&h.app, card.center()), "{key} must shield the viewport"); + } + let inspector = h.app.shell.workspace_panels["render:inspector"].0; + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + let ribbon_bottom = h.app.shell.cards.iter().map(|r| r.bottom()).fold(0.0, f32::max); + assert!((browser.top() - inspector.top()).abs() < 1.0); + assert!((appearances.bottom() - inspector.bottom()).abs() < 1.0); + assert!(browser.height() <= 330.0, "Browser must stay within the fixed tree height: {browser:?}"); + for key in ["render:browser", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + assert!( + (card.top() - ribbon_bottom - Tokens::get().space_8).abs() < 1.0, + "{layout:?} {key}: gap {} must be 8 pt", + card.top() - ribbon_bottom + ); + } + for key in ["render:browser", "render:appearances", "render:inspector"] { + let card = h.app.shell.workspace_panels[key].0; + let header = crate::scenario::rect_of(&format!("{key}:header")).unwrap(); + assert!((header.height() - crate::ui_kit::header_height()).abs() < 0.1, "{key}: {header:?}"); + assert!((header.top() - card.top()).abs() <= 1.0, "header must have no outer content padding"); + let control = crate::scenario::rect_of(if key == "render:browser" { + "render:tree:by-look" + } else if key == "render:appearances" { + "render:library-search" + } else if page == inspector::Page::Appearance { + "dialog:editor_footer" + } else { + "render:scene:look" + }) + .unwrap(); + if key == "render:browser" { + assert!(header.contains_rect(control), "Scene lens belongs in the title band"); + } else { + assert!(control.top() >= header.bottom(), "editor controls must be below the standard header: {control:?} {header:?}"); + } + } + + assert!((browser.width() - appearances.width()).abs() < 1.0); + assert!((appearances.top() - browser.bottom() - Tokens::get().space_8).abs() < 1.0); + assert!(appearances.bottom() < shots.top()); + assert!(browser.left() > viewport.left() && inspector.right() < viewport.right()); + assert!(inspector.bottom() < shots.top() && browser.bottom() < shots.top()); + let camera = h.app.cam; + h.step( + &json!({"drag":[[inspector.center().x,inspector.center().y],[inspector.center().x-30.0,inspector.center().y+20.0]],"button":"middle"}), + ) + .unwrap(); + assert_eq!(h.app.cam, camera, "middle dragging over the card must not reach the model"); + h.step(&json!({"click":{"handle":"render:shots:hide"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.viewport.rect, Some(viewport), "floating strips must preserve the viewport projection"); + let pill = h.app.shell.workspace_panels["render:shots:show"].0; + assert!(crate::shell::covered(&h.app, pill.center())); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert!(h.app.shell.workspace_panels.is_empty(), "Render card reservations must not leak into Design"); + } +} + +#[test] +fn render_workspace_assignment_footer_fits_stacked_card_with_shots_shown_and_hidden() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + for shown in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shown})).unwrap(); + h.frames(4); + let browser = h.app.shell.workspace_panels["render:browser"].0; + let appearances = h.app.shell.workspace_panels["render:appearances"].0; + // Assignment help is the shared footer's tooltip; its visible anchor stays in the card. + let footer = crate::scenario::rect_of("catalog:footer").unwrap(); + assert!(appearances.contains_rect(footer), "{layout:?}, Shots {shown}: footer {footer:?} outside {appearances:?}"); + let gap = Tokens::get().space_8; + assert!((appearances.top() - browser.bottom() - gap).abs() < 1.0); + let bounds = crate::shell::panel_bounds(&h.app, h.app.viewport.rect.unwrap()); + assert!((bounds.bottom() - appearances.bottom() - gap).abs() < 1.0, "{layout:?}, Shots {shown}: {appearances:?}, {bounds:?}"); + } + } +} + +#[test] +fn render_workspace_card_grips_swap_sides_and_resize_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + h.step(&json!({"drag":[{"handle":"render:inspector:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, "left"); + assert_eq!(h.app.preferences.render_browser_side, "right"); + assert!(h.app.shell.workspace_panels["render:inspector"].0.right() < h.app.shell.workspace_panels["render:browser"].0.left()); + let width = h.app.preferences.render_inspector_width; + let card_width = h.app.shell.workspace_panels["render:inspector"].0.width(); + let rail = crate::scenario::handle_at("render:inspector:resize").unwrap(); + h.step(&json!({"drag":[[rail.x,rail.y],[rail.x+50.0,rail.y]],"steps":8})).unwrap(); + h.frames(3); + // A compact dock keeps its minimum width and leaves the remembered width alone. + if layout == crate::shell::LayoutMode::Docked { + assert_eq!(h.app.preferences.render_inspector_width, width); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0.width(), card_width); + } else { + assert!(h.app.preferences.render_inspector_width > width); + assert!(h.app.shell.workspace_panels["render:inspector"].0.width() > card_width); + } + h.step(&json!({"click":{"handle":"render:tree:by-look"}})).unwrap(); + h.frames(3); + h.step(&json!({"drag":[{"handle":"render:browser:grip"},[100.0,350.0]],"steps":8})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_browser_side, "left"); + assert_eq!(h.app.preferences.render_inspector_side, "right"); + assert!(h.app.shell.workspace_panels["render:browser"].0.right() < h.app.shell.workspace_panels["render:inspector"].0.left()); + assert_eq!(h.app.cam, camera, "card gestures must not move the camera"); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } +} + +/// A small public-safe model, built through the sample recipe inside an occurrence. +fn render_pick_sample() -> (Harness, u64) { + let mut h = Harness::new(); + let part = h.app.run("component.create", json!({"name":"Sample","grounded":false})).unwrap(); + let occurrence = part["occurrence"].as_u64().unwrap(); + h.app.session.run_script(&solidcraft_engine::sample::script()).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.frames(4); + h.app.start("render.camera.fit"); + h.settle(); + (h, occurrence) +} + +fn product_pick_point(h: &Harness) -> egui::Pos2 { + let rect = h.app.viewport.layout.as_ref().unwrap().drawable; + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + for y in 2..18 { + for x in 2..18 { + let at = rect.min + egui::vec2(rect.width() * x as f32 / 20.0, rect.height() * y as f32 / 20.0); + if !crate::shell::covered(&h.app, at) + && crate::viewport::pick(&h.app, &proj, at).iter().any(|h| matches!(h, crate::viewport::Hit::Face { .. })) + { + return at; + } + } + } + panic!("sample must offer a visible product face outside the floating panels"); +} + +#[test] +fn render_workspace_pick_stage_tools_filter_sample_clicks_with_shots_shown_and_hidden() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for shots in [true, false] { + h.app.run("view.shots_strip", json!({"visible":shots})).unwrap(); + h.frames(3); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + assert!(tools.contains_rect(crate::scenario::rect_of("render:pick").unwrap())); + assert!(tools.contains_rect(crate::scenario::rect_of("render:preview_note").unwrap())); + assert!(crate::scenario::rect_of("render:hud").is_none()); + for mode in ["body", "face", "component"] { + assert!(crate::scenario::handle_at(&format!("render:pick:{mode}")).is_some(), "Pick must be enabled"); + h.step(&json!({"click":{"handle":format!("render:pick:{mode}")}})).unwrap(); + h.frames(2); + let at = product_pick_point(&h); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + assert!(matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. }))); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + match h.app.session.selection.as_slice() { + [Sel::Body { name }] if mode == "body" => assert_eq!(name, "Plate"), + [Sel::Face { body, .. }] if mode == "face" => assert_eq!(body, "Plate"), + [Sel::Occurrence { path }] if mode == "component" => assert_eq!(path, &[occurrence]), + other => panic!("{mode}, Shots {shots}: wrong selection {other:?}"), + } + let selected = h.app.session.selection.clone(); + enter(&mut h.app, false).unwrap(); + h.frames(3); + assert_eq!(h.app.session.selection, selected); + enter(&mut h.app, true).unwrap(); + h.settle(); + assert_eq!(h.app.session.selection, selected); + } + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.tool.is_none() && h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_click_modifiers_clear_and_browser_share_selection() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + for (name, x) in [("Left", -30), ("Right", 30)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":20,"width":20,"height":20,"body_name":name})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.settle(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let left = proj.to_screen(solidcraft_engine::geom::Vec3::new(-20.0, 10.0, 20.0)).unwrap(); + let right = proj.to_screen(solidcraft_engine::geom::Vec3::new(40.0, 10.0, 20.0)).unwrap(); + h.step(&json!({"click":[left.x,left.y]})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + h.step(&json!({"click":[left.x,left.y],"ctrl":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + h.app.preferences.selection_shift_add_only = true; + h.step(&json!({"click":[right.x,right.y],"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Right".into() }]); + // A Browser body row writes the same selection and immediately feeds the product overlay. + h.step(&json!({"click":{"handle":"row:Left"}})).unwrap(); + assert_eq!(h.app.session.selection, [Sel::Body { name: "Left".into() }]); + assert!(!crate::viewport::build_highlight(&h.app).merged().tris.is_empty()); + let empty = h.app.viewport.layout.as_ref().unwrap().drawable.left_bottom() + egui::vec2(10.0, -10.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.session.selection.is_empty()); + assert!(h.app.viewport.hover.is_none()); +} + +#[test] +fn render_workspace_selection_overlay_never_changes_started_frames_png_or_retained_results() { + use solidcraft_engine::Sel; + let (mut h, _) = render_pick_sample(); + let at = product_pick_point(&h); + let proj = crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let hit = crate::viewport::pick(&h.app, &proj, at).into_iter().next().unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let first = completed_preview(&mut h, [230, 230, 230]); + let clean = h.app.session.render_job_handle(first).unwrap().frame().unwrap().unwrap(); + let clean_scene = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + h.app.run("select.set", json!({"items":[face]})).unwrap(); + let face_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(!face_overlay.tris.is_empty()); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Plate".into() }]})).unwrap(); + let body_overlay = crate::viewport::build_highlight(&h.app).merged(); + assert!(body_overlay.tris.len() > face_overlay.tris.len(), "Face must only tint the selected face"); + h.app.viewport.hover = Some(hit); + let second = completed_preview(&mut h, [230, 230, 230]); + let selected = h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap(); + assert_eq!(clean.png(), selected.png(), "started image job must never capture selection or hover pixels"); + let after = gpu_scene(&solidcraft_engine::product_scene::extract(&h.app.session).unwrap()).unwrap(); + assert_eq!(clean_scene.0, after.0); + assert_eq!(clean_scene.1.tris, after.1.tris); + h.app.render_workspace.view.completed = Some(second); + h.app.render_workspace.view.result = true; + h.frames(3); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + h.step(&json!({"click":{"handle":"render:pick:body"}})).unwrap(); + assert!(!h.app.ui.pick_bodies && !h.app.ui.pick_components, "result canvas must disable the stage's Pick control"); + let path = h.dir.join("overlay-free.png"); + h.app.run("render.export", json!({"job":second,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), clean.png()); + assert_eq!(h.app.session.render_job_handle(second).unwrap().frame().unwrap().unwrap().png(), clean.png()); +} + +#[test] +fn render_workspace_pick_filter_rejects_invalid_requests_atomically() { + let mut h = Harness::new(); + let doc = h.app.session.doc.clone(); + for mode in ["body", "face", "component"] { + assert_eq!(h.app.run("select.filter", json!({"mode":mode})).unwrap()["mode"], mode); + assert_eq!(h.app.ui.pick_bodies, mode == "body"); + assert_eq!(h.app.ui.pick_components, mode == "component"); + } + for request in [json!({}), json!({"mode":"edge"}), json!({"mode":"body","extra":true})] { + assert!(h.app.run("select.filter", request).is_err()); + assert!(!h.app.ui.pick_bodies && h.app.ui.pick_components); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(h.app.session.undo.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_product_pass_draws_only_requested_face_or_body_overlay() { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(256.0, 256.0)); + app.viewport.rect = Some(rect); + let proj = crate::viewport::projection(&app, rect); + let hit = crate::viewport::pick(&app, &proj, rect.center()).into_iter().find(|h| matches!(h, crate::viewport::Hit::Face { .. })).unwrap(); + let face = crate::viewport::hit_sel(&hit).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&app.session).unwrap(); + let gpu = gpu_scene(&scene).unwrap().1; + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(app.cam.target); + let eye = app.cam.eye().to_f32(); + let camera = app.cam; + let draw = |overlay| { + crate::gpu::render_product_offscreen( + gpu.clone(), + overlay, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], 1.0], + 256, + false, + ) + }; + let Some(clean) = draw(None) else { + eprintln!("skipping: no GPU adapter for product overlay pixels"); + return; + }; + app.run("select.set", json!({"items":[face]})).unwrap(); + let face_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + app.run("select.set", json!({"items":[{"type":"body","name":"Product"}]})).unwrap(); + let body_pixels = draw(Some(crate::viewport::build_highlight(&app))).unwrap(); + let changed = |image: &[u8]| clean.as_chunks::<4>().0.iter().zip(image.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); + assert!(changed(&face_pixels) > 100, "Face overlay must reach the product pass"); + assert!(changed(&body_pixels) > changed(&face_pixels) + 100, "Face must leave the other faces untouched"); +} + +#[test] +fn render_workspace_pick_projection_matches_orthographic_and_custom_perspective_camera() { + use egui::{Event, Modifiers, PointerButton}; + use solidcraft_engine::geom::Vec3; + for fov in [0.0, 0.6, 1.1] { + let mut app = nav_app(true, "fusion", crate::prefs::OrbitAround::ViewCentre); + app.cam.fov = fov; + let ctx = crate::fonts::test_context(); + let mut time = 0.0; + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![]); + let rect = app.viewport.rect.unwrap(); + let proj = crate::viewport::projection(&app, rect); + assert_eq!(proj.cam.fov, fov); + let (x, y, _) = app.cam.to_screen(Vec3::new(20.0, 15.0, 20.0), f64::from(rect.width()), f64::from(rect.height()), 100.0).unwrap(); + let pos = rect.min + egui::vec2(x as f32, y as f32); + nav_frame(&mut app, &ctx, true, &mut time, Modifiers::NONE, vec![Event::PointerMoved(pos)]); + assert!(matches!(app.viewport.hover, Some(crate::viewport::Hit::Face { .. })), "FOV {fov}"); + for pressed in [true, false] { + nav_frame( + &mut app, + &ctx, + true, + &mut time, + Modifiers::NONE, + vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], + ); + } + assert!(matches!(app.session.selection.as_slice(), [solidcraft_engine::Sel::Face { body, .. }] if body == "Product"), "FOV {fov}"); + } +} + +#[test] +fn render_workspace_component_filter_keeps_nested_repeated_occurrences_distinct() { + use crate::viewport::{Hit, candidate}; + use solidcraft_engine::{Sel, geom::Vec3}; + let mut h = Harness::new(); + let parent = h.app.run("component.create", json!({"name":"Parent"})).unwrap(); + let child = h.app.run("component.create", json!({"name":"Part"})).unwrap(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Solid"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + let second = h.app.run("occurrence.copy", json!({"occurrence":parent["occurrence"],"translate":[50,0,0]})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"component"})).unwrap(); + for top in [parent["occurrence"].as_u64().unwrap(), second["occurrence"].as_u64().unwrap()] { + let path = vec![top, child["occurrence"].as_u64().unwrap()]; + let names = h.app.session.occurrence_bodies(&path, true).unwrap(); + assert_eq!(names.len(), 1); + let hit = Hit::Face { body: names[0].clone(), index: 0, point: Vec3::ZERO }; + assert_eq!(candidate(&h.app, &[hit]).unwrap().1, Sel::Occurrence { path }); + } +} + +#[test] +fn navigation_bar_render_canvases_filter_slots_and_keep_product_fit() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.preferences.look_at_anim = false; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps::RENDER); + // The product preview picks (#6426), so the slots that need a pick are on the bar there too. + for slot in ["orbit", "pan", "zoom", "fit", "look_at", "home", "visual_style", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } + h.app.cam.pan(100.0, 50.0, 600.0); + let panned = h.app.cam; + h.step(&json!({"click":{"handle":"nav:slot:fit"}})).unwrap(); + assert_ne!(h.app.cam.target, panned.target, "Fit recentres the product"); + assert_product_fits_canvas(&h.app); + let mut iso = h.app.cam; + iso.set_view(solidcraft_engine::render::StandardView::Iso); + h.app.cam.orbit(0.4, 0.2); + h.step(&json!({"click":{"handle":"nav:slot:home"}})).unwrap(); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (iso.yaw, iso.pitch), "Home returns to the isometric view"); + assert_product_fits_canvas(&h.app); + + let job = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.result = true; + h.settle(); + assert_eq!(crate::navigation_bar::canvas_caps(&h.app), crate::navigation::NavCaps { orbit: false, pick: false }); + for slot in ["orbit", "look_at", "visual_style"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_none(), "{slot}"); + } + for slot in ["pan", "zoom", "fit", "home", "display"] { + assert!(crate::scenario::handle_at(&format!("nav:slot:{slot}")).is_some(), "{slot}"); + } +} + +#[test] +fn render_lights_browser_sections_and_lights_describe_current_job_entries() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.frames(3); + let rows: Vec<_> = crate::browser::drawn_rows().into_iter().map(|r| r.0).collect(); + for section in ["Environment", "Lights", "Shots", "Objects"] { + assert!(rows.iter().any(|label| label == section), "{section}: {rows:?}"); + } + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3]); + assert_eq!(scene::environment(&h.app).0, "Fixed studio"); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "lights":[{"direction":[0,0,-1],"color":[1,1,1],"intensity":1}], + "punctual_lights":[ + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1}, + {"position_mm":[0,0,10],"color":[1,1,1],"intensity":1,"reference_distance_mm":10,"minimum_distance_mm":0.1, + "cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}} + ], + "area_lights":[{"center_mm":[0,0,10],"edge_u_mm":[1,0,0],"edge_v_mm":[0,-1,0],"color":[1,1,1],"intensity":1}] + })) + .unwrap(); + assert_eq!(scene::light_types(&h.app), ["render.tree_directional", "render.tree_point", "render.tree_spot", "render.tree_rectangle"]); + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.punctual_lights = None; + h.app.render_workspace.view.raytrace.area_lights = None; + assert!(scene::light_types(&h.app).is_empty(), "empty explicit rig must stay empty"); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let studio = &mut h.app.render_workspace.view.studio; + studio.sun_enabled = true; + assert_eq!(scene::light_types(&h.app), vec!["render.tree_directional"; 3], "implicit studio sources are listed"); + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app + .render_workspace + .view + .studio + .area_lights + .push(serde_json::from_value(json!({"center":[0,0,10],"u":[1,0,0],"v":[0,-1,0],"radiance":[1,1,1]})).unwrap()); + assert_eq!(scene::light_types(&h.app), ["render.tree_sun", "render.tree_rectangle"]); + h.app.render_workspace.view.studio.environment = studio::Environment::Sky; + h.app.render_workspace.view.studio.rotation_rad = std::f64::consts::FRAC_PI_2; + h.app.render_workspace.view.studio.intensity = 2.5; + assert_eq!(scene::environment(&h.app), ("Sky".into(), "90° · 2.50×".into())); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:environment:current"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + h.step(&json!({"click":{"browser":"Key"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); +} + +#[test] +fn render_workspace_browser_look_lens_counts_distinct_objects_and_selects_them() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + for (name, x) in [("A", 0), ("B", 20), ("C", 40)] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + } + h.app.run("appearance.assign", json!({"bodies":["A","B"],"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["C"],"appearance":"ABS - Blue"})).unwrap(); + // Two faces on C use the same look as A and B: still only one additional user. + h.app.run("appearance.assign", json!({"body":"C","faces":[[40,5,5],[45,0,5]],"appearance":"ABS - Red"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let groups = scene::groups(&h.app); + let red = groups.iter().position(|g| g.look.as_ref().is_some_and(|l| l.name == "ABS - Red")).unwrap(); + assert_eq!(groups[red].objects, ["A", "B", "C"]); + assert_eq!(groups.len(), 2); + h.app.render_workspace.view.by_look = true; + // Keep the object rows inside the ten-row Browser viewport while testing their hover. + crate::browser::toggle(&mut h.app, "render:tree:lights", true); + h.frames(3); + let at = crate::scenario::handle_at("row:A").unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.frames(2); + assert_eq!(h.app.viewport.hover_bodies, ["A"], "By look rows retain Browser hover outlines"); + h.step(&json!({"move":[1000.0,800.0]})).unwrap(); + h.frames(2); + assert!(h.app.viewport.hover_bodies.is_empty(), "leaving the row clears its hover outline"); + h.step(&json!({"click":{"handle":format!("render:tree:look:{red}")}})).unwrap(); + assert_eq!(h.app.session.selection.len(), 3); + for name in ["A", "B", "C"] { + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: name.into() })); + } + h.step(&json!({"click":{"handle":"eye:A"}})).unwrap(); + assert!(h.app.session.visibility.hidden_bodies.contains(&"A".into())); + let menu = crate::context_menu::items(&h.app, &crate::context_menu::Target::Body { name: "A".into() }); + for id in ["select.set", "select.same_look", "ui.isolate", "ui.show"] { + assert!(menu.iter().any(|i| i.id == id)); + } +} + +#[test] +fn render_workspace_dock_command_swaps_sides_without_design_edits() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + let product_camera = h.app.render_workspace.view.draft.camera; + let widths = (h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width); + assert!(crate::shortcut_box::search(&h.app, "view.render_dock").iter().any(|row| row.0 == "view.render_dock")); + for (panel, side, inspector, browser) in [ + ("inspector", "left", "left", "right"), + ("browser", "left", "right", "left"), + ("inspector", "right", "right", "left"), + ("browser", "right", "left", "right"), + ] { + h.app.run("view.render_dock", json!({"panel":panel,"side":side})).unwrap(); + h.frames(3); + assert_eq!(h.app.preferences.render_inspector_side, inspector); + assert_eq!(h.app.preferences.render_browser_side, browser); + let a = h.app.shell.workspace_panels["render:inspector"].0; + let b = h.app.shell.workspace_panels["render:browser"].0; + assert_eq!(a.center().x < b.center().x, inspector == "left"); + let view = h.app.viewport.layout.as_ref().unwrap(); + assert!(view.content.contains_rect(view.axis_view)); + let edge = if inspector == "left" { view.axis_view.left() - view.content.left() } else { view.content.right() - view.axis_view.right() }; + assert!(edge.abs() < 0.1); + assert!(!view.navigation.intersects(a)); + assert!(!view.navigation.intersects(b)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.render_workspace.view.draft.camera, product_camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + assert_eq!((h.app.preferences.render_browser_width, h.app.preferences.render_inspector_width), widths); + } + } +} + +#[test] +fn render_workspace_dock_grip_menus_dispatch_the_other_side() { + for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.app.ui.layout = layout; + h.call("ui.resize", json!({"width":1600,"height":1000})); + enter(&mut h.app, true).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + for panel in ["inspector", "inspector", "browser", "browser"] { + let before = h.app.preferences.render_inspector_side.clone(); + let at = crate::scenario::handle_at(&format!("render:{panel}:grip")).unwrap(); + for pressed in [true, false] { + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }, + ]); + } + h.frames(2); + // Opening the menu must not move either panel. + assert_eq!(h.app.preferences.render_inspector_side, before); + h.step(&json!({"click":{"handle":format!("render:{panel}:move_side")}})).unwrap(); + h.frames(3); + assert_ne!(h.app.preferences.render_inspector_side, before); + assert_ne!(h.app.preferences.render_inspector_side, h.app.preferences.render_browser_side); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc, document); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history); + } + } +} + +#[test] +fn render_workspace_browser_shot_switch_keeps_the_existing_dirty_confirmation() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1100})); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{"width":321,"job":{"method":"raster"}}})).unwrap(); + h.app.render_workspace.view.draft.width = 123; + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "A"); + assert!(inspector::confirmation_open(&h.app)); + h.step(&json!({"widget":h.app.tr("render.keep_editing")})).unwrap(); + assert_eq!(h.app.render_workspace.view.draft.width, 123); + h.step(&json!({"click":{"handle":"render:tree:shot:B"}})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.discard_continue")})).unwrap(); + assert_eq!(h.app.render_workspace.view.name, "B"); + assert_eq!(h.app.render_workspace.view.draft.width, 321); + assert!(!h.app.render_workspace.view.dirty); +} + +#[test] +fn render_lights_browser_focus_covers_each_kind_without_design_edits() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + h.app.run("render.settings.set", json!({"name":"Shot","set":{"job":{"method":"raster"}}})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.studio.lighting_enabled = true; + h.app.render_workspace.view.studio.sun_enabled = true; + h.frames(3); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for label in ["Environment", "Lights", "Shots", "Objects", "Output"] { + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == label), "{label}"); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.step(&json!({"click":{"handle":"row:Object"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Object(vec![Sel::Body { name: "Object".into() }])); + h.step(&json!({"click":{"handle":"render:tree:environment"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Environment); + assert!(crate::scenario::rect_of("dialog:section:Source").is_some()); + assert!(h.app.session.selection.is_empty()); + let focused_revision = h.app.session.revision; + h.step(&json!({"click":{"handle":"render:tree:light:0"}})).unwrap(); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Light(id) if id=="directional:0")); + setups::load(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:shot:Shot"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Shot("Shot".into())); + // The browser is height-capped even in a tall window. Output is its last row, + // and published targets can lie below the scroll clip as more rows are added. + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + h.call("ui.scroll", json!({"x":browser.center().x,"y":(header.bottom()+browser.bottom())/2.0,"delta":-2000})); + h.frames(20); + let browser = crate::scenario::rect_of("browser:card").unwrap(); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + let output = crate::scenario::handle_at("render:tree:output").unwrap(); + assert!( + browser.shrink(Tokens::get().space_8).contains(output) && output.y > header.bottom(), + "Output click must be inside the visible browser body" + ); + h.step(&json!({"click":{"handle":"render:tree:output"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + h.app.run("view.render_select", json!({"kind":"nothing"})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert_eq!(h.app.session.revision, focused_revision, "semantic selection only refreshes the view when clearing object picks"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +#[test] +fn render_lights_browser_eye_and_solo_are_view_state_and_editor_opening_is_read_only() { + let mut h = render_lights_fixture(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Key")); + assert!(crate::browser::drawn_rows().iter().any(|row| row.0 == "Fill")); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty()); + h.step(&json!({"click":{"handle":"eye:Key"}})).unwrap(); + assert!(!h.app.render_workspace.view.lights.visibility.visible("directional:0")); + h.step(&json!({"click":{"handle":"render:tree:light:1:solo"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.lights.visibility.solo.as_deref(), Some("directional:1")); + h.step(&json!({"click":{"handle":"render:tree:light:1"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + assert!(crate::scenario::handle_at("render:tree:shots:add").is_some()); + h.step(&json!({"click":{"handle":"render:tree:shots:add"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Scene); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision, h.app.session.is_dirty())); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.dialog.is_none()); +} + +#[test] +fn render_workspace_browser_stage_expansion_never_locks_rows_or_changes_focus() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + let doc = h.app.session.doc.clone(); + let sections = ["objects", "lights", "environment", "shots"]; + for (stage, expanded) in [("look", vec!["objects"]), ("light", vec!["lights", "environment"]), ("frame", vec!["shots"]), ("output", vec![])] { + for section in sections { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + for section in sections { + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), expanded.contains(§ion), "{stage}/{section}"); + crate::browser::toggle(&mut h.app, &format!("render:tree:{section}"), true); + assert_eq!(crate::browser::is_open(&h.app, &format!("render:tree:{section}"), true), !expanded.contains(§ion)); + } + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); +} + +#[test] +fn render_workspace_browser_semantic_focus_survives_clearing_object_picks() { + use solidcraft_engine::Sel; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Object"})).unwrap(); + enter(&mut h.app, true).unwrap(); + let doc = h.app.session.doc.clone(); + let evaluated = h.app.session.world_state(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + for (request, expected) in [ + (json!({"kind":"environment"}), RenderSelection::Environment), + (json!({"kind":"lighting"}), RenderSelection::Lighting), + (json!({"kind":"light","id":"sun"}), RenderSelection::Light("sun".into())), + (json!({"kind":"shot","id":"Shot"}), RenderSelection::Shot("Shot".into())), + (json!({"kind":"output"}), RenderSelection::Output), + (json!({"kind":"nothing"}), RenderSelection::Nothing), + ] { + h.app.run("select.set", json!({"items":[Sel::Body { name:"Object".into() }]})).unwrap(); + assert!(matches!(h.app.render_workspace.view.selection, RenderSelection::Object(_))); + h.app.run("view.render_select", request.clone()).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.selection, expected, "{request}"); + assert!(h.app.session.selection.is_empty()); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert!(Arc::ptr_eq(&evaluated, &h.app.session.world_state())); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); +} + +#[test] +fn render_workspace_browser_focus_is_per_document_and_invalid_selection_is_atomic() { + let mut h = Harness::new(); + h.app.run("view.render_select", json!({"kind":"environment"})).unwrap(); + let doc = h.app.session.doc.clone(); + for request in [ + json!({}), + json!({"kind":"object"}), + json!({"kind":"light"}), + json!({"kind":"shot","id":""}), + json!({"kind":"lighting","id":"extra"}), + json!({"kind":"output","id":"x"}), + json!({"kind":"shot","id":"x".repeat(1025)}), + json!({"kind":"nothing","extra":1}), + ] { + assert!(h.app.run("view.render_select", request).is_err()); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Nothing); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + crate::documents::switch(&mut h.app, 0); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Environment); + crate::documents::switch(&mut h.app, 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Output); +} + +#[test] +fn render_workspace_wear_tree_selects_the_scene_stack_and_counts_layers_in_both_lenses() { + use solidcraft_engine::render::job::aging::{AgingKind, AgingLayer}; + fn has_text(shape: &egui::Shape, needle: &str) -> bool { + match shape { + egui::Shape::Text(text) => text.galley.text().contains(needle), + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, needle)), + _ => false, + } + } + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1440,"height":1400})); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10,"body_name":"Subject"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body { name: "Subject".into() }]})).unwrap(); + let document = h.app.session.doc.clone(); + assert_eq!(scene::wear_subtitle(&h.app), h.app.tr("render.wear_no_layers")); + h.frames(3); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, h.app.tr("render.wear_no_layers")))); + h.step(&json!({"click":{"handle":"render:tree:wear"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Wear); + assert!(h.app.session.selection.is_empty()); + assert!(crate::scenario::rect_of("render:wear:controls").is_some()); + assert!(!crate::icon_svg::resolve("appearance").placeholder); + for count in 1..=2 { + h.app.render_workspace.view.studio.aging.push(AgingLayer::preset(AgingKind::Dust)).unwrap(); + h.app.render_workspace.view.dirty = true; + let label = + crate::i18n::format(if count == 1 { "render.wear_layer_one" } else { "render.wear_layer_count" }, &[("count", &count.to_string())]); + assert_eq!(scene::wear_subtitle(&h.app), label); + for by_look in [false, true] { + h.app.run("view.render_browser", json!({"by_look":by_look})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:tree:wear").is_some()); + assert!(h.shapes.iter().any(|s| has_text(&s.shape, &label))); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); +} + +/// Actual application tree at the approved card width, in both themes and both task states. +#[test] +fn render_workspace_browser_compact_geometry_search_and_theme_evidence() { + let previous = crate::theme::is_dark(); + let mut themes = Vec::new(); + for dark in [false, true] { + let mut h = Harness::new(); + for (name, x, appearance) in [ + ("Plate", 0, "Aluminum - Satin"), + ("Boss", 20, "Aluminum - Anodized Blue"), + ("Knob", 40, "Copper"), + ("Cover", 60, "Glass - Clear"), + ("Spacer", 80, "Aluminum - Satin"), + ("Bolt", 100, "Aluminum - Satin"), + ("Nut", 120, "Aluminum - Satin"), + ] { + h.app.run("solid.box", json!({"corner":[x,0,0],"length":10,"width":10,"height":10,"body_name":name})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":[name],"appearance":appearance})).unwrap(); + } + let group = + h.app.run("browser.group", json!({"folder":"bodies","name":"Spacer, fasteners","items":["Spacer","Bolt","Nut"]})).unwrap()["group"] + .as_u64() + .unwrap(); + h.app.tree.collapsed.insert(format!("c0/g{group}")); + for name in ["Hero", "Front", "Detail"] { + h.app.run("render.settings.set", json!({"name":name,"set":{"width":1920,"height":1080}})).unwrap(); + } + enter(&mut h.app, true).unwrap(); + h.app.preferences.render_browser_width = 266.0; + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + h.app.ui.dark = dark; + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + let mut images = Vec::new(); + for stage in ["look", "light"] { + h.app.run("view.render_stage", json!({"stage":stage})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.lights = Some(serde_json::from_value(json!([{"direction":[0,0,-1],"color":[1,1,1],"intensity":1},{"direction":[1,0,0],"color":[1,1,1],"intensity":1},{"direction":[0,1,0],"color":[1,1,1],"intensity":1}])).unwrap()); + for section in ["lights", "shots", "objects"] { + if (stage == "look" && section == "objects") || (stage == "light" && section == "lights") { + h.app.tree.collapsed.remove(&format!("render:tree:{section}")); + } else { + h.app.tree.collapsed.insert(format!("render:tree:{section}")); + } + } + if stage == "light" { + h.app + .run( + "view.render_select", + json!({"kind":"light","id":format!("{}:render.tree_directional:0",h.app.render_workspace.view.method.label())}), + ) + .unwrap(); + } + let mut image = None; + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(bounds), + time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), + focused: true, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let card = crate::scenario::rect_of("browser:card").unwrap(); + assert!((card.width() - 266.0).abs() < 0.1); + let inspector = crate::scenario::rect_of("render:inspector").unwrap(); + let stage_panel = h.app.shell.workspace_panels["render:appearances"].0; + assert!((card.top() - inspector.top()).abs() < 0.1); + assert!((stage_panel.bottom() - inspector.bottom()).abs() < 0.1); + assert!((stage_panel.top() - card.bottom() - Tokens::get().space_8).abs() < 0.1); + assert!(card.height() <= 330.0, "Browser must stay within the fixed tree height: {card:?}"); + let header = crate::scenario::rect_of("render:browser:header").unwrap(); + assert!(header.contains_rect(crate::scenario::rect_of("render:tree:by-look").unwrap())); + assert!(crate::scenario::handle_at("render:browser-model").is_none()); + assert!(crate::scenario::handle_at("render:browser-library").is_none()); + for (name, row, _, _) in crate::browser::drawn_rows() { + assert!((row.height() - 28.0).abs() < 0.1, "{name}: {row:?}"); + } + if stage == "look" { + let row = crate::browser::drawn_rows().into_iter().find(|r| r.0 == "Boss").unwrap().1; + assert!((row.width() - (card.width() - 2.0)).abs() < 0.1); + assert!(crate::scenario::handle_at("eye:Boss").unwrap().x > row.right() - 24.0); + } + if std::env::var_os("SOLIDCRAFT_BROWSER_EVIDENCE").is_some() { + let full = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image = Some( + image::imageops::crop_imm(&full, card.left() as u32, card.top() as u32, card.width() as u32, card.height() as u32) + .to_image(), + ); + } + } + } + if let (Some(image), Ok(dir)) = (image, std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + std::fs::create_dir_all(&dir).unwrap(); + image.save(std::path::Path::new(&dir).join(format!("scene-{stage}-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + images.push(image); + } + } + if let (Some(look), Some(light), Ok(dir)) = (images.first(), images.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + let mut pair = image::RgbaImage::new(look.width() + light.width(), look.height().max(light.height())); + image::imageops::overlay(&mut pair, look, 0, 0); + image::imageops::overlay(&mut pair, light, 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-stages-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + themes.push(images); + h.app.run("view.render_browser", json!({"search":true,"query":"Copper"})).unwrap(); + h.app.tree.collapsed.remove("render:tree:objects"); + h.frames(4); + let rows = crate::browser::drawn_rows(); + assert!(rows.iter().any(|r| r.0 == "Knob")); + assert!(!rows.iter().any(|r| r.0 == "Boss")); + h.app.run("view.render_browser", json!({"search":false})).unwrap(); + h.frames(3); + assert!(crate::browser::drawn_rows().iter().any(|r| r.0 == "Boss")); + for hidden in [true, false] { + h.step(&json!({"click":{"handle":"eye:Boss"}})).unwrap(); + assert_eq!(h.app.session.visibility.hidden_bodies.iter().any(|name| name == "Boss"), hidden); + } + } + if let (Some(light), Some(dark), Ok(dir)) = (themes.first(), themes.get(1), std::env::var("SOLIDCRAFT_BROWSER_EVIDENCE")) { + for (index, stage) in ["look", "light"].iter().enumerate() { + let mut pair = image::RgbaImage::new(light[index].width() + dark[index].width(), light[index].height().max(dark[index].height())); + image::imageops::overlay(&mut pair, &light[index], 0, 0); + image::imageops::overlay(&mut pair, &dark[index], 266, 0); + pair.save(std::path::Path::new(&dir).join(format!("scene-{stage}-themes.png"))).unwrap(); + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_workspace_shots_modified_dot_update_and_revert_follow_only_camera() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + setups::save(&mut h.app).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Camera; + h.frames(3); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + let saved = h.app.session.doc.render.setups["Studio"].clone(); + h.app.render_workspace.view.draft.width = 317; + h.frames(2); + assert!(!shots::camera_modified(&h.app, "Studio"), "output settings must not mark the camera"); + h.app.cam.yaw += 0.3; + h.frames(3); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_some()); + assert!(crate::scenario::handle_at("render:shots:update").is_some()); + h.step(&json!({"click":{"handle":"render:shots:update"}})).unwrap(); + h.frames(2); + let mut expected = saved.clone(); + expected.camera = h.app.cam; + assert_eq!(h.app.session.doc.render.setups["Studio"], expected, "Update must preserve saved output and lighting"); + assert_eq!(h.app.render_workspace.view.draft.width, 317, "Update must preserve the editor draft"); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert!(crate::scenario::rect_of("dialog:list:shot:Studio:modified").is_none()); + assert!(crate::scenario::handle_at("render:shots:update").is_none()); + h.app.cam.roll += 0.2; + h.frames(3); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:revert"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.cam, expected.camera); + assert!(!shots::camera_modified(&h.app, "Studio")); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_workspace_shots_save_prompt_and_size_dropdown_use_existing_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:shots:save"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + h.app.render_workspace.view.save_shot_name = Some("Hero".into()); + h.frames(3); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(1.0)); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(h.app.session.doc.render.setups.contains_key("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.render.setups["Hero"].camera, h.app.cam); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:shots:size"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:list:Full HD"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1920, 1080)); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn render_workspace_shots_thumbnails_bound_invalidate_and_never_replace_results_or_history() { + use std::time::{Duration, Instant}; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + for index in 0..20 { + h.app.run("render.settings.set", json!({"name":format!("Shot {index:02}"),"set":{"camera":h.app.cam}})).unwrap(); + } + // A real completed frame stays available, including its exact PNG and retained texture. + let id = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + let png = h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png().to_vec(); + let retained = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let deadline = Instant::now() + Duration::from_secs(20); + while h.app.render_workspace.thumbnails.entries.len() < thumbnails::LIMIT { + assert!(Instant::now() < deadline, "thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(h.app.render_workspace.thumbnails.entries.len(), 16); + assert!(h.app.render_workspace.thumbnails.entries.values().all(|texture| texture.as_ref().is_some_and(|texture| texture.size() == [104, 60]))); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), retained); + assert_eq!(h.app.render_workspace.view.completed, Some(id)); + assert_eq!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().unwrap().png(), png); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(h.app.session.doc, doc); + assert_eq!(h.app.session.undo.len(), undo); + // Later shots must get previews on selection/scrolling rather than keeping the first 16 forever. + h.app.render_workspace.view.name = "Shot 19".into(); + h.app.render_workspace.thumbnails.show(vec!["Shot 18".into(), "Shot 19".into()], &h.ctx); + thumbnails::refresh(&mut h.app, &h.ctx); + while h.app.render_workspace.thumbnails.texture("Shot 19").is_none() || h.app.render_workspace.thumbnails.texture("Shot 18").is_none() { + assert!(Instant::now() < deadline, "visible thumbnail worker did not complete"); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.len() <= 16); + std::thread::sleep(Duration::from_millis(2)); + } + let old = h.app.render_workspace.thumbnails.entries.keys().cloned().collect::>(); + // Camera, scene revision and visibility invalidate stale previews. + let camera = Camera { yaw: 0.7, ..h.app.cam }; + h.app.run("render.settings.set", json!({"name":"Shot 00","set":{"camera":camera}})).unwrap(); + thumbnails::refresh(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.thumbnails.entries.keys().all(|key| !old.contains(key))); + h.app.session.visibility.hidden_bodies.push("Body1".into()); + thumbnails::refresh(&mut h.app, &h.ctx); + invalidate_scene(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); + thumbnails::refresh(&mut h.app, &h.ctx); + reset_document(&mut h.app); + assert!(h.app.render_workspace.thumbnails.entries.is_empty()); +} + +#[test] +fn render_workspace_shots_running_ring_stays_with_the_submitted_shot() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.name = "A".into(); + setups::save(&mut h.app).unwrap(); + h.app.run("render.settings.set", json!({"name":"B","set":{}})).unwrap(); + h.app.start("render.start"); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("A")); + h.app.render_workspace.view.name = "B".into(); + h.frames(2); + assert!(crate::scenario::rect_of("dialog:list:shot:A:progress").is_some()); + assert!(crate::scenario::rect_of("dialog:list:shot:B:progress").is_none()); + h.app.start("render.cancel"); +} + +#[test] +fn render_workspace_shots_thumbnail_keys_include_name_scene_revision_and_complete_camera() { + let camera = Camera::default(); + let key = thumbnails::Key::new("Hero".into(), 1, 2, camera); + assert_eq!(key, thumbnails::Key::new("Hero".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Front".into(), 1, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 2, 2, camera)); + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 3, camera)); + for changed in [ + Camera { yaw: camera.yaw + 0.1, ..camera }, + Camera { roll: camera.roll + 0.1, ..camera }, + Camera { fov: 0.7, ..camera }, + Camera { up: solidcraft_engine::render::UpAxis::Y, ..camera }, + ] { + assert_ne!(key, thumbnails::Key::new("Hero".into(), 1, 2, changed)); + } +} + +#[test] +fn render_workspace_shots_heading_matches_design_history_typography_and_strip_baseline() { + fn heading(h: &mut Harness, title: &str, strip: &str) -> (egui::FontId, Color32) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 1000.0))), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + let rect = crate::scenario::rect_of(strip).unwrap(); + let text = crate::test_support::text_shapes(&output).find(|text| text.galley.text() == title && rect.contains(text.pos)).unwrap(); + let format = &text.galley.job.sections.first().unwrap().format; + assert!((text.pos.y + text.galley.size().y / 2.0 - rect.center().y).abs() <= 1.0, "{title} centred on its strip"); + let appearance = (format.font_id.clone(), format.color); + output.textures_delta.clear(); + appearance + } + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.ui.layout = crate::shell::LayoutMode::Docked; + h.app.preferences.timeline_left = false; + h.app.ui.show_timeline = true; + h.frames(3); + let history = heading(&mut h, "History", "history:strip"); + enter(&mut h.app, true).unwrap(); + h.frames(3); + assert_eq!(heading(&mut h, "Shots", "render:shots_strip"), history); +} + +#[test] +fn render_workspace_frame_save_shot_dispatches_without_a_ribbon_or_document_edits() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(3); + assert!(crate::scenario::handle_at("render:stage:save_shot").is_none()); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:stage:save_shot"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc, document); + assert_eq!(h.app.session.undo.len(), undo); + h.app.render_workspace.view.save_shot_name = Some("Frame shot".into()); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Frame shot"].camera, h.app.cam); + h.app.render_workspace.view.save_shot_name = None; + assert!(h.app.run("render.settings.set", json!({})).is_err()); + assert!(!inspector::confirmation_open(&h.app)); + assert!(crate::workspace::destination(solidcraft_engine::find_command("view.shots_strip").unwrap()).is_none()); + assert!(crate::workspace::RIBBON_LABELS.iter().all(|(id, _)| *id != "view.shots_strip")); +} + +#[test] +fn render_workspace_shots_strip_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":15,"height":10})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.pending_fit = None; + for (name, yaw) in [("Hero", 0.5), ("Front", 0.0), ("Detail", 0.8)] { + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":Camera {yaw,..h.app.cam}}})).unwrap(); + } + switch_shot(&mut h.app, "Hero".into()); + h.app.render_workspace.view.draft.width = 1920; + h.app.render_workspace.view.draft.height = 1080; + let reply = h.app.session.execute("render.start", &json!({"settings":{"width":1920,"height":1080}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..10_000 { + host.pump(16_384).unwrap(); + if h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some() { + break; + } + } + assert!(h.app.session.render_job_handle(id).unwrap().frame().unwrap().is_some()); + h.app.render_workspace.view.job = Some(id); + cache_render_images(&mut h.app, &h.ctx); + h.app.render_workspace.view.job = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..12 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(bounds), time: Some(ctx.cumulative_frame_nr() as f64 / 60.0), ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 11 { + let strip = crate::scenario::rect_of("render:shots_strip").unwrap(); + assert!((strip.height() - 48.0).abs() < 1.0, "{strip:?}"); + let mut last = crate::scenario::rect_of("render:shots:heading").unwrap(); + for target in [ + "render:shots:save", + "render:shots:setup:Detail", + "render:shots:setup:Front", + "render:shots:setup:Hero", + "render:shots:status", + "render:shots:size", + "render:shots:render", + "render:shots:hide", + ] { + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(strip.contains_rect(rect), "{target}: {rect:?} in {strip:?}"); + assert!(rect.left() >= last.right(), "{target} overlaps preceding control"); + last = rect; + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_SHOTS_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("shots-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn appearance_editor_hostile_optics_stay_finite_and_never_panic() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":10,"height":3,"body_name":"Optics"})).unwrap(); + let target = materials::read_targets(&mut h.app).unwrap().remove(0); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + h.app.render_workspace.view.materials.enabled = true; + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1e300] { + let mut binding = materials::Binding::new(target.clone(), &h.app); + binding.glass_enabled = true; + binding.glass.ior = value; + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_err(), "hostile IOR {value}"); + } + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + h.app.render_workspace.view.materials.bindings = vec![binding]; + assert!(materials::params(&h.app, &mut json!({})).is_ok(), "box boundaries are closed dielectrics too"); +} + +fn output_viewer_fixture() -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"output"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.frames(3); + h +} + +#[test] +fn output_viewer_size_chips_obey_limits_and_largest_upscales_at_the_current_aspect() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for (key, expected) in [("720", (1280, 720)), ("1080", (1920, 1080))] { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + let draft = &h.app.render_workspace.view.draft; + assert_eq!((draft.width, draft.height), expected); + } + let largest = inspector::largest_output(&h.app).unwrap(); + assert!(largest.0 > 1920); + assert_eq!(cpu::image_limits(&h.app).fit(largest.0, largest.1, None), Some(largest)); + assert!((largest.0 as f64 / largest.1 as f64 - 16.0 / 9.0).abs() < 0.002); + h.step(&json!({"click":{"handle":"render:size:largest"}})).unwrap(); + assert_eq!((u64::from(h.app.render_workspace.view.draft.width), u64::from(h.app.render_workspace.view.draft.height)), largest); + let before = h.app.render_workspace.view.draft.clone(); + assert!(h.app.run("render.output.size", json!({"width":4096,"height":4096})).is_err()); + assert_eq!(h.app.render_workspace.view.draft, before); + assert_eq!(h.app.session.doc.features, document.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_check_lists_preflight_results_without_starting_and_marks_edits_stale() { + let mut h = output_viewer_fixture(); + let host = h.app.session.render_job_host().unwrap().clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:stage:check"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.checked.is_none()); + h.step(&json!({"click":{"handle":"render:check"}})).unwrap(); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!(host.admitted_bytes(), 0); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + h.app.run("render.output.size", json!({"width":32,"height":16})).unwrap(); + h.frames(2); + assert!(crate::scenario::rect_of("render:check:stale").is_some()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_copy_uses_retained_final_pixels_and_refuses_missing_or_oversized_images() { + let mut h = output_viewer_fixture(); + assert!(ribbon::perform_job(&mut h.app, "render.result.copy").is_err()); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(decode_render_image(&[], 4097, 1, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + assert!(decode_render_image(&[], 4096, 4096, RenderLimits::default(), 4096).unwrap_err().contains("resource profile")); + let first = completed_preview(&mut h, [12, 34, 56]); + h.app.render_workspace.view.completed = Some(first); + // A new queued render must not become the source for Copy. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + ribbon::perform_job(&mut h.app, "render.result.copy").unwrap(); + let image = h.app.render_workspace.clipboard_image.as_ref().unwrap(); + assert_eq!(image.size, [16, 16]); + assert_eq!(image.pixels[0], egui::Color32::from_rgb(12, 34, 56)); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame(); + assert!(h.app.render_workspace.clipboard_image.is_none()); + assert!(h.output.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyImage(image) if image.size == [16,16]))); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(undo, h.app.session.undo.len()); +} + +#[test] +fn output_viewer_progress_keeps_stage_tools_and_cancel_cancels_without_closing_viewer() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.result = true; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_some()); + assert!(crate::scenario::rect_of("render:stage:size").is_some()); + assert!(crate::scenario::rect_of("render:hud").is_none()); + h.step(&json!({"click":{"handle":"render:progress-cancel"}})).unwrap(); + h.app.session.render_job_host().unwrap().pump(1024).unwrap(); + assert_eq!(h.app.session.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"], "cancelled"); + assert!(h.app.render_workspace.view.result); + h.frames(3); + assert!(crate::scenario::rect_of("render:progress-pill").is_none()); + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::handle_at("render:pick").is_some()); +} + +#[test] +fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cancelling() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.name = "Active shot".into(); + h.app.render_workspace.view.draft.width = 32; + h.app.render_workspace.view.draft.height = 24; + assert_eq!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); + h.step(&json!({"key":"R"})).unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + assert_eq!(h.app.render_workspace.view.job_shot.as_deref(), Some("Active shot")); + let status = h.app.session.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(status["request"]["width"], 32); + assert_eq!(status["request"]["height"], 24); + // A repeated R while busy cannot fall through to Rectangle/Create Sketch. + h.step(&json!({"key":"R"})).unwrap(); + assert_eq!(h.app.render_workspace.view.job, Some(job)); + assert!(h.app.dialog.is_none() && h.app.tool.is_none()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.frames(2); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + assert!(ribbon::busy(&h.app), "closing the image never cancels the job"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); + crate::keymap::press(&mut h.app, "Escape", false); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.viewport.nav.is_none(), "closing the image releases its navigation capture"); + enter(&mut h.app, false).unwrap(); + assert_ne!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); +} + +/// Actual app controls and retained pixels, rasterized from egui without a window. +#[test] +fn output_viewer_evidence() { + let Some(dir) = std::env::var_os("SOLIDCRAFT_OUTPUT_EVIDENCE") else { return }; + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.run("solid.box", json!({"length":24,"width":18,"height":12})).unwrap(); + inspector::fit_subject(&mut h.app).unwrap(); + h.app.pending_fit = None; + h.app.cancel_view_animation(); + h.app.preferences.render_inspector_width = 305.0; + h.app.run("render.output.size", json!({"width":1280,"height":720})).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + h.ctx = crate::fonts::test_context(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + crate::theme::set_dark(dark); + crate::theme::apply(&h.ctx); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for (index, state) in ["settings", "check", "effects", "running", "completed"].into_iter().enumerate() { + if state == "check" { + h.app.run("view.render_select", json!({"kind":"check"})).unwrap(); + h.app.cancel_view_animation(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + if state == "effects" { + select_image_method(&mut h.app, ImageMethod::GpuRaytrace); + h.app.start("render.effects.describe"); + } + if state == "running" { + select_image_method(&mut h.app, ImageMethod::Raster); + h.app.run("view.render_select", json!({"kind":"output"})).unwrap(); + // Retain a real first image while the next job makes bounded progress. + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.completed.is_some()); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + host.pump(327680).unwrap(); + assert!(ribbon::busy(&h.app)); + } + if state == "completed" { + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..1000 { + if !host.pump(65536).unwrap() { + break; + } + } + } + for frame in 0..10 { + let mut events = Vec::new(); + if frame == 0 { + events.push(egui::Event::PointerMoved(egui::pos2(700.0, 500.0))); + } + let mut input = egui::RawInput { + screen_rect: Some(bounds), + focused: true, + time: Some((index * 10 + frame) as f64 / 60.0), + events, + ..Default::default() + }; + h.app.raw_input_hook(&mut input); + let mut output = h.ctx.run_ui(input, |ui| { + h.app.logic(ui.ctx()); + if state == "check" && frame == 9 { + // Check the settled, scrolled view immediately before capturing it. + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + } + h.app.ui(ui); + }); + crate::ui_kit::update_test_textures(&mut textures, &output.textures_delta); + if frame == 9 { + if state == "check" { + for key in ["ready", "size", "transparency"] { + assert!(crate::scenario::rect_of(&format!("render:check:{key}")).is_some(), "{key}"); + } + assert!(h.app.render_workspace.view.job.is_none()); + } + crate::ui_kit::raster_ui(&h.ctx, output.shapes.clone(), output.pixels_per_point, bounds, &textures) + .save(dir.join(format!("output-{state}-{}.png", if dark { "dark" } else { "light" }))) + .unwrap(); + } + output.textures_delta.clear(); + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled() { + let h = output_viewer_fixture(); + let expected = [ + "render.start", + "appearance.assign", + "render.lights.add", + "render.settings.set", + "render.camera.fit", + "render.compare", + "ui.workspace.design", + "undo", + ]; + assert_eq!(crate::mouse_gesture::Studio::Render.defaults(), expected); + assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); + assert!(!crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); +} + +#[test] +fn output_viewer_presets_are_commands_with_limits_and_custom_keeps_the_size() { + let mut h = output_viewer_fixture(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frames(6); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "opening Size presets does not apply anything"); + for (index, (key, expected)) in [("720", (1280, 720)), ("1080", (1920, 1080)), ("square", (2048, 2048))].into_iter().enumerate() { + h.step(&json!({"click":{"handle":format!("render:preset:{key}")}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), expected); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + let saved = &h.app.session.doc.render.setups[&h.app.render_workspace.view.name]; + assert_eq!((saved.width, saved.height), expected); + } + h.step(&json!({"click":{"handle":"render:preset:4k"}})).unwrap(); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + h.step(&json!({"click":{"handle":"render:preset:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.inspector.resolution.custom); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (2048, 2048)); + assert_eq!(document.features, h.app.session.doc.features); + assert_eq!(undo + 3, h.app.session.undo.len()); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to_output() { + for dark in [false, true] { + let mut h = output_viewer_fixture(); + h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); + h.app.ui.dark = dark; + h.call("ui.resize", json!({"width":1440,"height":900})); + h.frames(3); + for key in ["render.children.renderer", "render.output_image", "render.output_destination", "render.children.render"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).is_some(), "{key}"); + } + assert!(crate::scenario::rect_of("render:job-footer").is_none()); + for page in ["output", "effects", "all"] { + assert!(crate::scenario::rect_of(&format!("render:page:{page}")).is_none()); + } + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for target in ["render:stage:size", "render:stage:check"] { + assert!(tools.contains_rect(crate::scenario::rect_of(target).unwrap())); + } + h.app.run("view.render_stage", json!({"stage":"look"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:output-width").is_some(), "selected Output keeps its editor when the stage changes"); + } +} + +#[test] +fn render_assign_gestures_selection_sizes_are_atomic_and_undoable() { + use solidcraft_engine::Sel; + let (mut h, occurrence) = render_pick_sample(); + for mode in ["body", "face", "component"] { + h.app.run("select.filter", json!({"mode":mode})).unwrap(); + let at = product_pick_point(&h); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), false).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + match mode { + "body" => assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"), + "face" => assert!(h.app.session.doc.appearances.faces.iter().any(|f| f.look.name == "ABS - Blue")), + _ => { + let id = h.app.session.doc.path_placement(&[occurrence]).unwrap().0; + assert_eq!(h.app.session.doc.appearances.components[&id].name, "ABS - Blue"); + } + } + assert!(h.app.status_undo); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Plate".into() }, Sel::Body { name: "missing".into() }]; + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + assert!(assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).is_err()); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} + +#[test] +fn render_assign_gestures_paint_sample_copy_paste_escape_and_failed_pick() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let before = h.app.session.doc.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), false).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + h.frames(3); + let at = product_pick_point(&h); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 2); + h.step(&json!({"widget":"Undo"})).unwrap(); + assert_eq!(h.app.session.undo.len(), undo + 1, "toast Undo must not paint through to the canvas"); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.run("appearance.assign", json!({"body":"Plate","faces":[[20,20,8]],"appearance":"ABS - Blue"})).ok(); + h.app.start("appearance.pick_up"); + let candidate = crate::viewport::pick(&h.app, &crate::viewport::projection(&h.app, h.app.viewport.rect.unwrap()), at) + .into_iter() + .find(|hit| matches!(hit, crate::viewport::Hit::Face { .. })) + .unwrap(); + let source = match candidate { + crate::viewport::Hit::Face { body, index, .. } => Some((body, index)), + _ => None, + }; + let (body, index) = source.unwrap(); + let expected = h.app.run("appearance.pick_up", json!({"target":{"body":body,"face":index}})).unwrap()["look"].clone(); + h.step(&json!({"click":[at.x,at.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.painting); + assert_eq!(h.app.render_workspace.view.assign.look, Some(expected.clone())); + h.step(&json!({"widget":"Done"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting); + h.app.start("appearance.paint"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Plate".into() }]; + h.app.start("appearance.copy"); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Yellow"})).unwrap(); + let undo = h.app.session.undo.len(); + h.app.start("appearance.paste"); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); + h.app.start("appearance.pick_up"); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + // Empty view: a failed pick neither paints nor exits sampling. + let free = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + let empty = egui::pos2(free.right() - 20.0, free.bottom() - 50.0); + h.step(&json!({"click":[empty.x,empty.y]})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.render_workspace.view.assign.sampling); +} + +#[test] +fn render_assign_gestures_drag_preview_and_release_use_no_document_draft() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + let at = product_pick_point(&h); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + ]); + h.frames(2); + assert!(assign::preview(&h.app).is_some()); + let mut scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let before = scene.meshes.iter().map(|m| m.color).collect::>(); + assign::preview_scene(&mut scene, assign::preview(&h.app).as_ref()).unwrap(); + assert_ne!(scene.meshes.iter().map(|m| m.color).collect::>(), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.frame_with(vec![egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }]); + h.frames(2); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), document.to_json()); +} + +#[test] +fn render_assign_gestures_shortcuts_are_scoped_and_commands_are_not_stubs() { + let mut h = Harness::new(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("inspect.measure")); + enter(&mut h.app, true).unwrap(); + assert_eq!(crate::keymap::command_for(&h.app, "I"), Some("appearance.pick_up")); + assert_eq!(crate::keymap::command_for(&h.app, "B"), Some("appearance.paint")); + for (id, key) in [("appearance.copy", "Ctrl+Alt+C"), ("appearance.paste", "Ctrl+Alt+V")] { + assert_eq!(crate::keymap::command_for(&h.app, key), Some(id)); + } + for id in ["appearance.paint", "appearance.pick_up", "appearance.copy", "appearance.paste"] { + assert!(solidcraft_engine::find_command(id).unwrap().planned.is_none()); + } + let before = h.app.session.doc.clone(); + h.app.run("appearance.paint", json!({"appearance":"ABS - Red"})).unwrap(); + h.app.run("appearance.pick_up", json!({})).unwrap(); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(h.app.dialog.is_none()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[test] +fn render_assign_gestures_grid_drag_modifiers_cancel_and_context_menu() { + let (mut h, occurrence) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"name":"Gesture blue","color":"#1234dd"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + h.step(&json!({"click":{"handle":"render:library-scope:in-design"}})).unwrap(); + h.frames(3); + let id = json!(["Gesture blue", "#1234dd", 1.0, null]).to_string(); + let source = crate::scenario::rect_of(&format!("render:library:{id}")).unwrap().center(); + let at = product_pick_point(&h); + let doc = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.frame_with(vec![egui::Event::PointerMoved(source)]); + h.frame_with(vec![egui::Event::PointerButton { + pos: source, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }]); + h.frame_with(vec![egui::Event::PointerMoved(source + egui::vec2(20.0, 0.0))]); + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frames(2); + assert!(assign::preview(&h.app).is_some(), "grid drag must arm a live preview over geometry"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + for mods in [egui::Modifiers::SHIFT, egui::Modifiers::CTRL, egui::Modifiers::COMMAND] { + h.frame_with(vec![egui::Event::ModifiersChanged(mods)]); + h.frames(2); + let hover = assign::hover(&h.app).unwrap(); + if mods.shift { + assert!(matches!(hover, solidcraft_engine::Sel::Face { .. })); + } else { + assert_eq!(hover, &solidcraft_engine::Sel::Occurrence { path: vec![occurrence] }); + } + assert!(assign::preview(&h.app).is_some()); + } + h.frame_with(vec![ + egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::SHIFT }, + ]); + h.frames(2); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.faces.last().unwrap().look.name, "Gesture blue"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + h.step(&json!({"move":[at.x,at.y]})).unwrap(); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(assign::preview(&h.app).is_none()); + assert_eq!(h.app.session.doc.to_json(), doc.to_json()); + let menu = assign::menu(&h.app, "Plate"); + for id in ["appearance.library", "appearance.pick_up", "appearance.copy", "appearance.paste", "appearance.assign"] { + assert!(menu.children.iter().any(|item| item.id == id), "missing menu action {id}"); + } + let browse = menu.children.iter().find(|item| item.id == "appearance.library").unwrap(); + crate::context_menu::run_item(&mut h.app, browse, at); + assert!(h.app.dialog.is_none()); + assert!(!h.app.render_workspace.view.assign.painting); +} + +#[test] +fn render_assign_gestures_labels_translate_in_all_five_catalogs() { + for language in ["en", "ja", "zh", "de", "ko"] { + let locale = crate::i18n::Locale::for_language(language); + for id in [ + "cmd.appearance_copy", + "cmd.appearance_paste", + "render.assign_help", + "render.browse_looks", + "render.choose_look", + "render.look_applied", + "render.painting_with", + "render.pick_up_prompt", + "render.recent_looks", + "render.remove_override", + "cmd.appearance_favorite", + "render.replace_all", + "render.replace_with", + "render.look_material", + "render.hover_look", + ] { + assert_ne!(locale.text(id), id, "{language}: {id}"); + } + assert!(locale.format("render.painting_with", &[("name", "Sample")]).contains("Sample")); + } +} + +#[test] +fn render_lighting_group_selection_opens_ordered_editor_and_plus_still_adds() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + let before = h.app.session.doc.clone(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:tree:lights"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Lighting); + assert!(crate::scenario::rect_of("render:lighting:editor").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + let sections: Vec<_> = ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] + .iter() + .map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()) + .collect(); + assert!(sections.windows(2).all(|pair| pair[0].bottom() <= pair[1].top())); + h.step(&json!({"click":{"handle":"render:tree:lights:add"}})).unwrap(); + assert!(light::rows(&h.app).unwrap().iter().any(|l| l.geometry.kind() == "area")); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Light("area:0".into())); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_methods_show_reasons_and_budgets_without_changing_method_or_design() { + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + if method == ImageMethod::GpuRaytrace { + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":"gpu_path","options":{"lighting":{}}}}})).unwrap(); + setups::load(&mut h.app); + } else { + h.app.render_workspace.view.method = method; + } + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + let before = h.app.session.doc.clone(); + let revision = h.app.session.revision; + h.frames(3); + for section in ["render.lighting_source_section", "render.lighting_shadows_section", "render.lighting_budget"] { + assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(section))).is_some()); + } + let reason = match method { + ImageMethod::Raster => "render.method_limit_raster", + ImageMethod::CpuRaytrace => "render.lighting_samples_need_area", + ImageMethod::GpuRaytrace => "render.light_gpu_punctual", + }; + assert!(crate::scenario::rect_of(&format!("dialog:note:{reason}")).is_some()); + if method == ImageMethod::GpuRaytrace { + assert!(crate::scenario::rect_of("dialog:note:render.lighting_shadow_cpu").is_some()); + assert!(crate::scenario::rect_of("dialog:note:render.lighting_samples_cpu").is_some()); + } + assert!(h.widget(h.app.tr("render.lighting_budget_help")).is_some()); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.session.revision, revision); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert!(h.app.dialog.is_none() && h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn render_assign_gestures_stage_tools_and_selection_actions_use_commands() { + let (mut h, _) = render_pick_sample(); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(4); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + assert!(crate::workspace::destination(solidcraft_engine::find_command(id).unwrap()).is_none()); + } + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!(pill.width() < 200.0, "{pill:?}"); + for index in 0..4 { + assert!(pill.contains_rect(crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap())); + } + h.step(&json!({"click":{"handle":"render:stage:appearance.pick_up"}})).unwrap(); + assert!(h.app.render_workspace.view.assign.sampling); + h.step(&json!({"key":"Escape"})).unwrap(); + h.step(&json!({"click":{"handle":"selection:action:0"}})).unwrap(); + assert!(crate::scenario::rect_of("render:look_chain").is_some()); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), 1); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert!(h.app.preferences.render_library_favorites.is_empty()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + h.step(&json!({"click":{"handle":"selection:action:1"}})).unwrap(); + assert!(inspector::confirmation_open(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.step(&json!({"click":{"handle":"dialog:Replace with"}})).unwrap(); + h.step(&json!({"widget":"Copper"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert!(!inspector::confirmation_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "Copper"); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"selection:action:3"}})).unwrap(); + assert!(!h.app.session.body_visible("Plate")); + h.app.run("edit.undo", json!({})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"light"})).unwrap(); + h.frames(3); + assert!(crate::scenario::rect_of("render:selection").is_none()); + assert!(crate::scenario::rect_of("render:stage:appearance.paint").is_none()); +} + +#[test] +fn render_assign_gestures_replacement_draft_cannot_cross_a_document_edit() { + let (mut h, _) = render_pick_sample(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Plate".into()}]})).unwrap(); + h.app.start("appearance.replace"); + assert!(assign::replacement_open(&h.app)); + h.app.run("appearance.assign", json!({"bodies":["Plate"],"appearance":"ABS - Red"})).unwrap(); + h.frames(3); + assert!(!assign::replacement_open(&h.app)); + assert_eq!(h.app.session.doc.appearances.bodies["Plate"].name, "ABS - Red"); +} + +#[test] +fn render_assign_gestures_geometry_and_theme_evidence() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.run("solid.cylinder", json!({"body_name":"Boss","radius":10,"height":20})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Boss"],"appearance":"Aluminum - Anodized Blue"})).unwrap(); + h.app.run("solid.sphere", json!({"body_name":"Knob","center":[0,0,28],"radius":8})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Knob"],"appearance":"Copper"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Boss".into()}]})).unwrap(); + h.app.pending_fit = None; + h.app.ui.dark = dark; + let ctx = crate::fonts::test_context(); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); + let mut textures = std::collections::HashMap::new(); + for frame in 0..48 { + crate::scenario::clear_handles(); + let events = h + .app + .viewport + .rect + .and_then(|rect| crate::viewport::projection(&h.app, rect).to_screen(solidcraft_engine::geom::Vec3::new(0.0, 0.0, 28.0))) + .filter(|_| frame == 1) + .map(|at| vec![egui::Event::PointerMoved(at)]) + .unwrap_or_default(); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), time: Some(frame as f64 / 60.0), events, ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + crate::ui_kit::test_textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + if frame == 47 { + assert!( + crate::scenario::rect_of("kit:tooltip").is_some(), + "the model hover uses the standard kit tooltip; hover: {:?}, pointer: {:?}", + h.app.viewport.hover, + ctx.pointer_hover_pos() + ); + let tooltip = crate::scenario::rect_of("kit:tooltip").unwrap(); + assert!(tooltip.distance_to_pos(ctx.pointer_hover_pos().unwrap()) < Tokens::get().control_height, "{tooltip:?}"); + let pill = crate::scenario::rect_of("render:selection").unwrap(); + assert!((pill.height() - 34.0).abs() < 1.0, "{pill:?}"); + assert!((150.0..170.0).contains(&pill.width()), "{pill:?}"); + let tools = crate::scenario::rect_of("render:stage_tools").unwrap(); + for id in ["appearance.paint", "appearance.pick_up"] { + assert!(tools.contains_rect(crate::scenario::rect_of(&format!("render:stage:{id}")).unwrap())); + } + if let Ok(dir) = std::env::var("SOLIDCRAFT_GESTURES_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let image = crate::ui_kit::test_raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures); + image.save(std::path::Path::new(&dir).join(format!("look-controls-{}.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn render_lights_each_kind_contains_design_sections_and_real_parameter_fields_in_order() { + for (method, kind) in + [("cpu_raytrace", "area"), ("cpu_raytrace", "point"), ("cpu_raytrace", "directional"), ("gpu_path", "area"), ("gpu_path", "directional")] + { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":3000})); + let options = if method == "gpu_path" { json!({"lighting":{}}) } else { json!({"lights":[],"punctual_lights":[],"area_lights":[]}) }; + h.app.run("render.settings.set", json!({"name":"Studio","set":{"job":{"method":method,"options":options}}})).unwrap(); + setups::load(&mut h.app); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":kind}))).unwrap(); + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + let before = h.app.session.doc.clone(); + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); + let mut sections = vec!["render.light_position"]; + if kind == "area" { + sections.push("render.lighting_shape"); + } + if kind == "point" { + sections.push("render.lighting_falloff"); + } + sections.push("render.light_behaviour"); + let rects: Vec<_> = sections.iter().map(|key| crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).unwrap()).collect(); + assert!(rects.windows(2).all(|pair| pair[0].bottom() <= pair[1].top()), "{method}/{kind}"); + let fields: &[&str] = match kind { + "area" => &["width_mm", "height_mm", "radiance:0", "edge_u_mm:0", "edge_v_mm:0", "position_mm:0"], + "point" => &["reference_distance_mm", "minimum_distance_mm", "position_mm:0"], + _ => &["direction:0", "direction:1", "direction:2"], + }; + for field in fields { + assert!(crate::scenario::rect_of(&format!("render:light:{field}")).is_some(), "{method}/{kind}: {field}"); + } + for key in ["render.lighting_solo", "render.lighting_mute", "render.light_duplicate", "render.light_delete"] { + assert!(h.widget(h.app.tr(key)).is_some(), "{method}/{kind}: {key}"); + } + assert!(crate::scenario::rect_of("dialog:note:render.light_place_pending").is_some()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + } +} + +#[test] +fn render_lighting_preset_materialises_values_and_replacement_requires_review_consent() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + // Confirm's primary action is disabled until its explicit acknowledgement. + h.step(&json!({"widget":h.app.tr("render.lighting_consent")})).unwrap(); + h.step(&json!({"widget":h.app.tr("render.lighting_apply")})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_some()); + assert!(h.app.render_workspace.view.raytrace.lights.is_none()); + let lights = light::rows(&h.app).unwrap(); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"render:lighting:custom"}})).unwrap(); + assert!(h.app.render_workspace.view.raytrace.preset.is_none()); + assert_eq!(h.app.render_workspace.view.raytrace.lights.as_ref().unwrap().len(), lights.len()); + let materialised = light::rows(&h.app).unwrap(); + for (before, after) in lights.iter().zip(materialised) { + assert_eq!(before.colour, after.colour); + assert_eq!(before.intensity, after.intensity); + } + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.render_workspace.view.selection, RenderSelection::Lighting); +} + +#[test] +fn render_lighting_hostile_numeric_edits_refuse_without_panics_or_partial_state() { + let mut h = render_lights_fixture(); + light::edit(&mut h.app, "render.lights.add", None, Some(json!({"kind":"point"}))).unwrap(); + let before = h.app.session.doc.clone(); + let history = h.app.session.undo.len(); + for set in + [json!({"reference_distance_mm":1e300}), json!({"minimum_distance_mm":-1}), json!({"position_mm":[1e300,0,0]}), json!({"direction":[0,0,0]})] + { + assert!(light::edit(&mut h.app, "render.lights.set", Some("point:0"), Some(set)).is_err()); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), history); + } + h.app.render_workspace.view.inspector.page = inspector::Page::Lighting; + h.frames(3); + assert!(crate::scenario::rect_of("render:light:editor").is_some()); +} + +#[test] +fn render_lighting_shadow_edits_are_undoable_and_preset_reviews_reject_changed_drafts() { + let mut h = render_lights_fixture(); + h.call("ui.resize", json!({"width":1440,"height":2400})); + h.app.run("view.render_select", json!({"kind":"lighting"})).unwrap(); + h.frames(3); + let before = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":h.app.tr("render.lighting_shadows")})).unwrap(); + assert!(!h.app.render_workspace.view.raytrace.shadows); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert!(matches!(&h.app.session.doc.render.setups["Studio"].job, + Some(solidcraft_engine::doc::render_settings::RenderJob::CpuRaytrace { options }) if !options.shadows)); + h.app.run("edit.undo", json!({})).unwrap(); + setups::load(&mut h.app); + assert_eq!(h.app.session.doc, before); + h.frames(3); + h.step(&json!({"click":{"handle":"render:lighting:preset"}})).unwrap(); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_some()); + h.app.render_workspace.view.draft.width = 1200; + h.frames(3); + assert!(h.widget(h.app.tr("render.lighting_consent")).is_none()); + assert_eq!(h.app.session.doc, before); + assert_eq!(h.app.render_workspace.view.draft.width, 1200); +} + +#[test] +fn geometry_budget_follows_the_device_buffer_limit_and_keeps_the_web_cap() { + // The standard 256 MiB device buffers: 2 GiB, far past the old fixed 128 MiB. + assert_eq!(geometry_budget(256 << 20, false), 2 << 30); + assert!(admit_geometry(129 << 20, geometry_budget(256 << 20, false)).is_ok()); + // A smaller device gets less, a larger one no more than the ceiling. + assert_eq!(geometry_budget(64 << 20, false), 512 << 20); + assert_eq!(geometry_budget(u64::MAX, false), DESKTOP_GEOMETRY_CEILING); + for device in [0, 256 << 20, u64::MAX] { + let budget = geometry_budget(device, true); + assert_eq!(budget, 128 << 20); + assert!(admit_geometry(budget, budget).is_ok()); + assert!(admit_geometry(budget + 1, budget).is_err()); + } +} + +#[test] +fn geometry_refusal_reports_scene_size_limit_and_recovery() { + use solidcraft_engine::{ + geom::{Aabb3, Mesh}, + render::ProductMesh, + }; + let scene = ProductScene { + meshes: vec![ProductMesh { + name: "Synthetic assembly".into(), + mesh: Arc::new(Mesh { triangles: vec![[0; 3]; 1 << 20], ..Default::default() }), + color: [128; 3], + opacity: 1.0, + surface: Some( + solidcraft_engine::render::surface::OpaqueSurface::new(solidcraft_engine::geom::Vec3::new(0.5, 0.5, 0.5), 0.0, 0.5, 1.5).unwrap(), + ), + transmission: None, + faces: Vec::new(), + }], + bounds: Aabb3::EMPTY, + }; + let error = gpu_scene_with_budget(&scene, WEB_GEOMETRY_BYTES).err().unwrap(); + assert!(error.contains("144.0 MiB"), "{error}"); + assert!(error.contains("128.0 MiB"), "{error}"); + assert!(error.contains("Hide bodies in Design"), "{error}"); + let refused = upload_refusal(144 << 20, "Out of Memory"); + assert!(refused.contains("144.0 MiB") && refused.contains("Out of Memory") && refused.contains("Hide bodies in Design"), "{refused}"); +} + +#[test] +fn previous_geometry_budget_restores_the_fixed_limit() { + for web in [false, true] { + for device in [64 << 20, 256 << 20, u64::MAX] { + let device_budget = geometry_budget(device, web); + assert_eq!(preferred_geometry_budget(device_budget, false), device_budget); + let previous = preferred_geometry_budget(device_budget, true); + assert_eq!(previous, MAX_GEOMETRY_BYTES as u64); + assert!(admit_geometry(previous, previous).is_ok()); + assert!(admit_geometry(previous + 1, previous).is_err()); + } + } +} + +#[test] +fn geometry_budget_change_retries_cached_admission_without_document_changes() { + let mut session = Session::default(); + session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&session).unwrap(); + let bytes = preview_upload_plan(&scene, usize::MAX).unwrap().bytes().unwrap() as u64; + let mut state = State::default(); + assert!(state.prepare_preview((7, 123, 99, bytes - 1), || Ok(scene.clone())).is_err()); + state.prepare_preview((7, 123, 99, bytes), || Ok(scene)).unwrap(); + assert_eq!(state.preview_upload_bytes, Some(bytes as usize)); + assert!(state.scene_error.is_none()); +} + +#[test] +fn cpu_interactive_cold_assembly_binding_refuses_without_preparing_world() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = Harness::new(); + let component = h.app.session.execute("component.create", &json!({"name":"Part","grounded":false})).unwrap(); + h.app.session.execute("solid.box", &json!({"length":10,"width":20,"height":5,"body_name":"Reflector"})).unwrap(); + let initial = h.app.session.world_state(); + let name = initial.bodies[0].name.clone(); + cpu::set_reflection(&mut h.app, &name, Some(ReflectionMode::Mirror)).unwrap(); + // Exact placement metadata changes without running a UI paint or world query. + let occurrence: u64 = serde_json::from_value(component["occurrence"].clone()).unwrap(); + h.app.session.pending_moves.insert(occurrence, solidcraft_engine::doc::IDENTITY); + assert!(h.app.session.interactive_cached_world_state().is_none()); + let model = h.app.session.model.state(); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + assert!(cpu::params_interactive(&h.app, &mut json!({})).unwrap_err().contains(h.app.tr("render.cpu_binding_stale"))); + assert!(h.app.session.interactive_cached_world_state().is_none(), "binding proof must not prepare cold placements"); + assert!(model.bodies.iter().all(|body| body.cached_mesh().is_none())); + cpu::set_reflection(&mut h.app, &name, None).unwrap(); + cpu::params_interactive(&h.app, &mut json!({})).unwrap(); + assert!(h.app.session.interactive_cached_world_state().is_none(), "empty reflections need no prepared world"); +} + +#[test] +fn interactive_egui_clock_is_finite_monotonic_and_requires_no_platform_instant() { + use std::time::Duration; + let mark = Duration::from_secs(2); + for time in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 1.0, f64::MAX] { + assert_eq!(interactive::monotonic(mark, time), mark); + } + assert_eq!(interactive::monotonic(mark, 3.5), Duration::from_millis(3500)); +} + +fn interactive_control_frame(h: &mut Harness, time: f64, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + events, + ..Default::default() + }, + |ui| { + ui.set_width(300.0); + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); +} + +#[test] +fn interactive_is_opt_in_and_refuses_raster_or_cooperative_hosts_without_fallback() { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + let document = h.app.session.doc.clone(); + let path = matches!(h.app.render_workspace.path_host, PathHost::NotStarted); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(matches!(h.app.render_workspace.path_host, PathHost::NotStarted), path); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_ui_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":8,"height":4,"body_name":"Subject"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::for_platform().unwrap(); + h.app.session.set_render_job_host(Some(host)).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + // Do not enter through a deferred GPU factory in CPU-only adapter tests. + h.app.ui.tab = "RENDER".into(); + h +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_test_cpu_branch(h: &mut Harness, case: &str) -> bool { + let host = h.app.session.render_job_host().unwrap(); + let supported = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + if supported { + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=true"); + return true; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + assert!(h.app.run("render.interactive", json!({"action":"on"})).is_err()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + eprintln!("INTERACTIVE_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + false +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_runtime_builder_preserves_hdr_ev_and_muted_lights_without_final_dimension_admission() { + let mut h = interactive_ui_fixture(); + let name = h.app.render_workspace.view.name.clone(); + h.app.run("render.settings.set", json!({"name":name,"set":{"job":{"method":"cpu_raytrace"}}})).unwrap(); + h.app.run("render.library.environment.apply", json!({"id":"HDR-001","name":name,"replace_environment":true})).unwrap(); + setups::load(&mut h.app); + assert!(h.app.render_workspace.view.cpu.hdr.embedded()); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.draft.exposure_ev = 1.5; + h.app.render_workspace.view.raytrace.shadows = false; + h.app.run("render.lights.mute", json!({"id":"directional:0","mute":true})).unwrap(); + let before = h.app.session.doc.clone(); + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["width"], 3840, "engine must fit before admission"); + assert!(wire["settings"]["job"].is_null()); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.5); + assert_eq!(wire["raytrace"]["shadows"], false); + assert_eq!(wire["raytrace"]["lights"][0]["intensity"], 0.0); + assert_eq!(wire["environment"]["resource"], json!(h.app.render_workspace.view.cpu.hdr.resource().unwrap())); + assert!(wire["environment"].get("path").is_none()); + assert!(raw_image_request(&h.app).is_err(), "final admission must remain unchanged"); + assert!(Arc::ptr_eq(&before, &h.app.session.doc)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_identity_tracks_camera_transport_and_visibility_before_paint_without_dispatching") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_control_frame(&mut h, 0.0, vec![]); + let first = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_control_frame(&mut h, 0.5, vec![]); + let camera = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(camera > first); + h.app.render_workspace.view.raytrace.shadows = false; + interactive_control_frame(&mut h, 1.0, vec![]); + let transport = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(transport > camera); + h.app.session.visibility.hidden_bodies.push("Subject".into()); + interactive_control_frame(&mut h, 1.5, vec![]); + let visibility = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + assert!(visibility > transport); + assert_eq!(h.app.session.revision, revision, "all three edits deliberately bypass CAD revision"); + assert_eq!(interactive::inspect(&h.app)["pending_capture"], false, "before_paint never dispatches a worker"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_command_controls_pause_resume_and_leave_without_changing_final_slots") { + return; + } + interactive_control_frame(&mut h, 0.0, vec![]); + let mut time = 0.01; + for action in ["on", "pause", "resume", "off"] { + let rect = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + let at = rect.center(); + interactive_control_frame( + &mut h, + time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }, + ], + ); + time += 0.01; + interactive_control_frame(&mut h, time, vec![]); + time += 0.01; + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + enter(&mut h.app, false).unwrap(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); +} + +#[test] +fn interactive_reset_retains_one_real_receiver_and_discards_its_late_foreign_error() { + use solidcraft_engine::render::job::interactive::{Interactive, VisualRevision}; + use std::{sync::mpsc, time::Duration}; + let mut h = Harness::new(); + let mut controller = Interactive::new(7001); + controller.enable(VisualRevision { scene_generation: 0, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = controller.capture(Duration::from_millis(200)).unwrap().unwrap(); + let (sender, receiver) = mpsc::channel(); + h.app.render_workspace.interactive.pending = Some(interactive::Pending { uid: h.app.session.uid, ticket, receiver }); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending()); + reset_document(&mut h.app); + assert!(h.app.render_workspace.interactive.pending(), "a second document reset cannot orphan the pending worker"); + sender.send(Err("late old capture".into())).unwrap(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert!(interactive::inspect(&h.app)["error"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_background_final_metadata_suspends_without_cancelling_queued_final() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_background_final_metadata_suspends_without_cancelling_queued_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + let job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + serde_json::from_value::(reply["job"].clone()).unwrap() + }; + let retained = host.admitted_bytes(); + interactive_control_frame(&mut h, 1.0, vec![]); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + let background = h.app.docs.background().next().unwrap(); + assert_eq!(background.render_job_handle(job).unwrap().status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert_eq!(host.admitted_bytes(), retained); + assert!(!h.app.render_workspace.interactive.pending()); +} + +// Native CPU acceptance of the real M3 dispatcher; no native window or GPU. +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveHeldCallback { + job: solidcraft_engine::render::job::JobHandle, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool, paint: bool) -> (egui::FullOutput, bool) { + let mut painted = false; + let output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(time), + ..Default::default() + }, + |ui| { + // tick dispatches through the actual production spawn(Snapshot) path. + // Do not run a second refresh here: the callback must be held before UI delivery. + if dispatch { + interactive::tick(&mut h.app, ui.ctx()); + } else { + interactive::before_paint(&mut h.app, ui.ctx()); + } + if paint { + painted = interactive::paint(&h.app, ui, ui.max_rect()); + } + }, + ); + (output, painted) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_clear_acceptance_frame(h: &mut Harness, time: f64, dispatch: bool) { + let (mut output, painted) = interactive_acceptance_frame(h, time, dispatch, false); + assert!(!painted); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_hold_real_completed_callback(h: &mut Harness) -> InteractiveHeldCallback { + use solidcraft_engine::render::job::Phase; + use std::{sync::mpsc, time::Duration}; + // The actual capture thread owns and invokes the real engine Snapshot.run. + // This test only withholds its actual returned message from the UI consumer. + // No tick/paint is called while the receiver is temporarily removed. + let mut pending = h.app.render_workspace.interactive.pending.take().expect("production tick must start a capture"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("real snapshot worker did not return"); + assert!(matches!(&reply, Ok(true)), "real snapshot must be adopted: {reply:?}"); + let job = + interactive::test_current(&h.app).expect("Interactive controller access must succeed").expect("Snapshot.run must attach the real CPU job"); + assert_eq!(job.id(), pending.ticket.job_id()); + assert_eq!(pending.uid, h.app.session.uid); + let status = job.wait_timeout(Duration::from_secs(60)).expect("real CPU job did not finish"); + assert_eq!(status.progress.phase, Phase::Completed); + assert!(status.error.is_none()); + assert_eq!(status.request.integrator, Integrator::Raytrace); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive.unwrap().samples_per_pixel, 16); + assert_eq!((status.request.width, status.request.height), (16, 16)); + let frame = job.frame().unwrap().expect("Completed requires real frame bytes"); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert_eq!(frame.info.job, job.id()); + assert_eq!(frame.info.scene_generation, pending.ticket.revision().scene_generation); + assert!(!frame.png().is_empty()); + assert_eq!(frame.info.png_bytes, frame.png().len() as u64); + { + use sha2::{Digest, Sha256}; + assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); + } + assert!(job.preview().unwrap().is_none(), "terminal image is distinct from the intermediate preview slot"); + // The renderer's Completed progress is normalized to 1/1, not an SPP counter. + assert_eq!((status.progress.done, status.progress.total), (1, 1)); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveHeldCallback { job, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_assert_final_export_isolation(h: &mut Harness, job: &solidcraft_engine::render::job::JobHandle) { + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.view.result); + assert!(h.app.render_workspace.image.is_none()); + assert!(!studio::linear_export_available(&h.app)); + let registry_error = h.app.session.render_job_handle(job.id()).err().expect("preview must not enter the final registry"); + assert!(registry_error.to_string().contains("WrongOwner"), "{registry_error}"); + let path = h.dir.join(format!("interactive-not-exportable-{}-{}.png", job.id().session, job.id().serial)); + assert!(!path.exists()); + let error = h.app.session.execute("render.export", &json!({"job":job.id(),"path":path,"format":"png"})).unwrap_err(); + // Require the actual preview/final ownership guard, rather than accepting a + // path/format/refusal error which would not prove final-registry isolation. + assert!(error.to_string().contains("WrongOwner"), "{error}"); + assert!(!path.exists()); + assert!(job.frame().unwrap().is_some(), "export refusal must not consume preview pixels"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_snapshot_worker_cpu16_png_is_cached_painted_reused_and_never_final_exported") { + return; + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + assert!(!h.app.render_workspace.interactive.pending()); + // Explicit egui time relative to the inherited clock crosses the 200 ms group; + // this does not wait on wall time or sleep to make a race likely. + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(interactive::test_cache(&h.app).is_none(), "worker completion alone must not fabricate a UI cache"); + let frame = held.job.frame().unwrap().unwrap(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + assert!(!h.app.render_workspace.interactive.pending()); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.job, held.job.id()); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!(samples, 16); + assert!(complete, "completed16 must use the completed key, still only in the provisional UI cache"); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + let uploaded = &output.textures_delta.set.get(&texture).expect("first real PNG publication must upload a texture").first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty())) + ); + let (mut repaint, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + assert!(!repaint.textures_delta.set.contains_key(&texture), "unchanged JobId/sequence/revision must reuse its texture"); + repaint.textures_delta.clear(); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_off_and_reenable_cannot_fill_new_cache_or_spawn_twice") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending(), "Off retains the single undrained receiver"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 1.0, true); + let pending = h.app.render_workspace.interactive.pending.as_ref().unwrap(); + assert_eq!(pending.ticket.job_id(), held.job.id(), "reactivation cannot replace an undrained capture"); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 1.1, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_pause_cannot_publish_unseen_old_pixels") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(h.app.render_workspace.interactive.pending()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(!painted, "Pause may retain already displayed pixels, but cannot adopt this unseen callback"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish() { + let mut h = interactive_ui_fixture(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_completed_callback_after_camera_edit_is_discarded_then_new_capture_can_publish") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.0, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let old = held.job.id(); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let revision = h.app.session.revision; + h.app.cam.yaw += 0.2; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert_eq!(h.app.session.revision, revision); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &held.job); + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + let newer = interactive_hold_real_completed_callback(&mut h); + assert_ne!(newer.job.id(), old); + newer.sender.send(newer.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, newer.job.id()); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &newer.job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +struct InteractiveRecoveryReply { + id: solidcraft_engine::render::job::JobId, + sender: std::sync::mpsc::Sender>, + reply: Result, +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_hold_reply(h: &mut Harness) -> InteractiveRecoveryReply { + use std::{sync::mpsc, time::Duration}; + let mut pending = h.app.render_workspace.interactive.pending.take().expect("actual tick must dispatch a Snapshot"); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).expect("actual capture worker did not return"); + let id = pending.ticket.job_id(); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + InteractiveRecoveryReply { id, sender, reply } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_missing_hdr(h: &mut Harness) -> (std::path::PathBuf, Vec) { + let path = h.dir.join("interactive-recovery-original.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + assert!(interactive_request(&h.app).is_ok(), "valid inspected metadata must reach actual worker preparation"); + std::fs::remove_file(&path).unwrap(); + (path, bytes) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_error(h: &mut Harness, time: f64) -> serde_json::Value { + interactive_clear_acceptance_frame(h, time, true); + let status = interactive::inspect(&h.app); + assert_eq!(status["phase"], "Error"); + assert!(status["error"].as_str().is_some_and(|error| !error.is_empty())); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none()); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + status["error"].clone() +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_recovery_require_success(h: &mut Harness, dispatch_time: f64, paint_time: f64) -> solidcraft_engine::render::job::JobId { + interactive_clear_acceptance_frame(h, dispatch_time, true); + let held = interactive_hold_real_completed_callback(h); + let id = held.job.id(); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(h, paint_time, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["samples"], 16); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, id); + interactive_assert_final_export_isolation(h, &held.job); + id +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_invalid_hdr_selection_never_dispatches_and_input_edit_can_recover") { + return; + } + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 2.0), error); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 2.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_recovery_require_success(&mut h, epoch + 2.301, epoch + 2.4); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit() { + for recovery in ["resume", "edit"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_real_hdr_file_error_latches_until_same_intent_resume_or_actual_input_edit:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let request = interactive_request(&h.app).unwrap(); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.as_ref().is_err_and(|error| !error.is_empty()), "missing HDR must fail actual preparation: {:?}", failed.reply); + assert!( + interactive::test_current(&h.app).expect("Interactive controller access must succeed").is_none(), + "preparation failure is not an admitted job-status failure" + ); + let failed_id = failed.id; + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + for offset in [0.6, 1.0] { + assert_eq!(interactive_recovery_require_error(&mut h, epoch + offset), error, "unchanged input must not retry"); + } + if recovery == "resume" { + std::fs::write(&path, bytes).unwrap(); + assert_eq!(interactive_request(&h.app).unwrap(), request, "repairing external bytes is not a UI intent edit"); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.1), error, "file repair alone cannot silently resume"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } else { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + assert!(interactive::inspect(&h.app)["error"].is_null()); + } + let new_id = interactive_recovery_require_success(&mut h, epoch + 1.301, epoch + 1.4); + assert_ne!(new_id, failed_id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_user_pause_survives_error_fixing_edit_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_user_pause_survives_error_fixing_edit_until_explicit_resume") { + return; + } + let _ = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + interactive_recovery_require_error(&mut h, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.4, false); + interactive_clear_acceptance_frame(&mut h, epoch + 2.0, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 2.201, epoch + 2.3); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_disconnected_real_callback_transport_latches_and_resume_creates_fresh_capture") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + assert!(held.reply.unwrap(), "native Snapshot/CPU work really finished before transport failure"); + // Deliberately close the actual std channel instead of fabricating an Err. + // This covers consumer Disconnected, not a claim that the native worker crashed. + drop(held.sender); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + assert_eq!(error, h.app.tr("render.interactive_error")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent() { + for recovery in ["edit", "resume"] { + let mut h = interactive_ui_fixture(); + let case = format!("interactive_late_real_preparation_error_cannot_overwrite_edited_or_resumed_intent:{recovery}"); + if !interactive_test_cpu_branch(&mut h, &case) { + continue; + } + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + if recovery == "edit" { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + } else { + std::fs::write(path, bytes).unwrap(); + // First consume clock input without consuming the still-held reply. + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + } + interactive_clear_acceptance_frame(&mut h, epoch + 0.501, true); + assert_eq!( + h.app.render_workspace.interactive.pending.as_ref().unwrap().ticket.job_id(), + failed.id, + "one old receiver still blocks new dispatch" + ); + failed.sender.send(failed.reply).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.6, false); + assert!(interactive::inspect(&h.app)["error"].is_null(), "actual old failure must be discarded"); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_cache(&h.app).is_none()); + let new_id = interactive_recovery_require_success(&mut h, epoch + 0.7, epoch + 0.8); + assert_ne!(new_id, failed.id); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_final_priority_never_clears_a_latched_error_or_retries_without_resume") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + let (path, bytes) = interactive_recovery_missing_hdr(&mut h); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let failed = interactive_recovery_hold_reply(&mut h); + assert!(failed.reply.is_err()); + failed.sender.send(failed.reply).unwrap(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.3); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.4), error); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).unwrap_err().contains(h.app.tr("render.interactive_final_active"))); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Queued); + // Only the test's explicit owner cancellation ends its queued final. + final_job.cancel().unwrap(); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 0.5), error); + std::fs::write(path, bytes).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.701, epoch + 0.8); + assert_eq!(final_job.status().unwrap().progress.phase, solidcraft_engine::render::job::Phase::Cancelled); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_actual_png_display_cap_error_latches_until_explicit_resume() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_actual_png_display_cap_error_latches_until_explicit_resume") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + held.sender.send(held.reply).unwrap(); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.3), + ..Default::default() + }, + |ui| { + // Real decoder admission against an invalid display capability; retain + // the real CPU PNG and restore input before fonts/end-frame processing. + let previous = ui.ctx().input(|input| input.max_texture_side); + ui.ctx().input_mut(|input| input.max_texture_side = 0); + interactive::before_paint(&mut h.app, ui.ctx()); + ui.ctx().input_mut(|input| input.max_texture_side = previous); + assert!(!interactive::paint(&h.app, ui, ui.max_rect())); + }, + ); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.4); + assert_eq!(error, h.app.tr("render.error_display_dimensions")); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error, "restoring display cap alone cannot rearm capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let newer = interactive_recovery_require_success(&mut h, epoch + 1.201, epoch + 1.3); + assert_ne!(newer, held.job.id()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_card_dimensions_use_real_paused_preview_not_changed_final_draft") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4), + ..Default::default() + }, + |ui| { + interactive::before_paint(&mut h.app, ui.ctx()); + interactive::controls(&mut h.app, ui); + }, + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + assert!(text.contains("16 × 16 px"), "actual cached dimensions must be visible: {text}"); + assert!(!text.contains("3840 × 2160 px"), "final draft cannot relabel the captured preview"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + let (info, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((info.width, info.height, samples, complete), (16, 16, 16, true)); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_card_bounds_avoid_current_selection_docks_and_navigation_at_wide_and_narrow_sizes() { + for (width, height) in [(1600.0, 1000.0), (760.0, 700.0)] { + let mut h = Harness::new(); + h.app.ui.tab = "RENDER".into(); + h.app.shell.workspace_panels.clear(); + let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let content = egui::Rect::from_min_max(egui::pos2(0.0, 132.0), egui::pos2(width, height - 56.0)); + let left = egui::Rect::from_min_max(egui::pos2(8.0, 140.0), egui::pos2(274.0, height - 64.0)); + let right = egui::Rect::from_min_max(egui::pos2(width - 313.0, 140.0), egui::pos2(width - 8.0, height - 64.0)); + crate::shell::register_panel(&mut h.app, "render:browser", Some(left), Some(crate::ui_kit::Edge::Left)); + crate::shell::register_panel(&mut h.app, "render:inspector", Some(right), Some(crate::ui_kit::Edge::Right)); + let centre = (left.right() + right.left()) / 2.0; + let navigation = egui::Rect::from_center_size(egui::pos2(centre, content.bottom() - 28.0), egui::vec2(120.0, 40.0)); + let axis = egui::Rect::from_min_size(egui::pos2(right.left() - 110.0, content.top()), egui::vec2(110.0, 110.0)); + h.app.viewport.layout = + Some(crate::viewport_layout::Layout { viewport, drawable: content, content, axis_view: axis, navigation, confirm: egui::Rect::NOTHING }); + // A new measured selection replaces the old one in this very frame. + // Both positions cut across the old top-centre status/action region. + for y in [content.top() + 90.0, content.top() + 180.0] { + let selection = egui::Rect::from_center_size(egui::pos2(centre, y), egui::vec2(180.0, 34.0)); + crate::shell::register_panel(&mut h.app, "render:selection", Some(selection), None); + let available = interactive::overlay_bounds(&h.app, content); + assert!(available.is_positive(), "{width}: no space for the Interactive card"); + assert!(content.contains_rect(available), "{width}: {available:?} outside {content:?}"); + for occupied in [selection, left, right, navigation, axis] { + assert!(!available.intersect(occupied).is_positive(), "{width}: {available:?} overlaps {occupied:?}"); + } + assert!(available.width() >= Tokens::get().control_height + Tokens::get().space_8); + } + assert!(!interactive::overlay_bounds(&h.app, egui::Rect::NOTHING).is_positive()); + assert_eq!(h.app.shell.workspace_panels["render:browser"].0, left); + assert_eq!(h.app.shell.workspace_panels["render:inspector"].0, right); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_overlay_keeps_real_selection_actions_and_pause_off_targets_accessible_without_dispatch() { + fn overlay_frame(h: &mut Harness, size: egui::Vec2, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, + |ui| { + // The shell clears Render reservations at the start of a real frame. + // Keep the already measured docks but never leave a previous selection + // rectangle that could make the moved-call regression pass by accident. + h.app.shell.workspace_panels.remove("render:selection"); + crate::render_ui::overlays(&mut h.app, ui); + }, + ); + output.textures_delta.clear(); + } + for size in [egui::vec2(1600.0, 1000.0), egui::vec2(760.0, 700.0)] { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_overlay_selection_controls") { + return; + } + h.call("ui.resize", json!({"width":size.x as u32,"height":size.y as u32})); + h.app.run("appearance.assign", json!({"bodies":["Subject"],"appearance":"ABS - Blue"})).unwrap(); + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body {name:"Subject".into()}]})).unwrap(); + h.frames(4); + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let selection_before = crate::scenario::rect_of("render:selection").unwrap(); + let actions_before: Vec<_> = (0..4).map(|index| crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap()).collect(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let camera = h.app.cam; + let docks = h.app.shell.workspace_panels.clone(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Paint the production overlays, but never tick or run a Snapshot worker. + for _ in 0..3 { + overlay_frame(&mut h, size, vec![]); + } + let card = crate::scenario::rect_of("render:interactive-card").unwrap(); + let selection = crate::scenario::rect_of("render:selection").unwrap(); + assert_eq!(selection, selection_before, "our card must not move the author's toolbar"); + assert!(!card.intersect(selection).is_positive()); + let content = crate::render_ui::canvas(&h.app, h.app.viewport.rect.unwrap()); + assert!(content.contains_rect(card), "{size:?}: {card:?} outside {content:?}"); + for (index, before) in actions_before.iter().enumerate() { + let action = crate::scenario::rect_of(&format!("selection:action:{index}")).unwrap(); + assert_eq!(&action, before); + assert!(selection.contains_rect(action)); + assert!(!card.intersect(action).is_positive(), "author action {index} is occluded"); + } + for action in ["pause", "off"] { + let target = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap(); + assert!(card.contains_rect(target), "{size:?}: {action} clipped outside {card:?}: {target:?}"); + assert!(!selection.intersect(target).is_positive()); + } + for action in ["pause", "off"] { + let at = crate::scenario::rect_of(&format!("render:interactive:{action}")).unwrap().center(); + for pressed in [true, false] { + overlay_frame( + &mut h, + size, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + overlay_frame(&mut h, size, vec![]); + assert_eq!(interactive::inspect(&h.app)["paused"], action == "pause"); + assert_eq!(interactive::inspect(&h.app)["enabled"], action != "off"); + assert!(!h.app.render_workspace.interactive.pending()); + } + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + for id in ["render:browser", "render:inspector", "render:appearances", "render:shots_strip"] { + let current = h.app.shell.workspace_panels.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + let before = docks.get(id).map(|(rect, edge)| (*rect, edge.as_ref().map(std::mem::discriminant))); + assert_eq!(current, before, "{id}"); + } + // With Interactive Off, the author's real hit target still dispatches. + let favorite_count = h.app.preferences.render_library_favorites.len(); + h.step(&json!({"click":{"handle":"selection:action:2"}})).unwrap(); + assert_eq!(h.app.preferences.render_library_favorites.len(), favorite_count + 1); + assert_eq!(crate::scenario::rect_of("render:selection").unwrap(), selection_before); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_waiting_show_text(h: &mut Harness, time: f64) -> String { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(time), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + let text = crate::test_support::text_shapes(&output).map(|shape| shape.galley.job.text.clone()).collect::>().join("\n"); + output.textures_delta.clear(); + text +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_uses_real_show_and_keeps_off_pause_error_and_result_routes") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "the fallback refusal is the real no-GPU positive control"); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + let fallback = h.app.tr("render.error_gpu_preview").to_string(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.01).contains(&fallback)); + + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let waiting = interactive_waiting_show_text(&mut h, epoch + 0.02); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!waiting.contains(&fallback), "real show must not enter the model-preview refusal while waiting"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "show/before_paint must not dispatch"); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.025, false, true); + assert!(!painted, "reserving the canvas does not claim an image was painted"); + output.textures_delta.clear(); + + h.app.render_workspace.view.result = true; + assert!(!interactive::awaiting_current_frame(&h.app), "the result view keeps priority"); + h.app.render_workspace.view.result = false; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.ui.tab = "MODEL".into(); + assert!(!interactive::awaiting_current_frame(&h.app)); + h.app.ui.tab = "RENDER".into(); + + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.03).contains(&fallback), "pause before any image keeps its existing fallback"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + assert!(!interactive_waiting_show_text(&mut h, epoch + 0.04).contains(&fallback)); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: h.dir.join("not-inspected.hdr").to_string_lossy().into_owned() }; + let error = interactive_waiting_show_text(&mut h, epoch + 0.05); + assert_eq!(interactive::inspect(&h.app)["phase"], "Error"); + assert!(!interactive::inspect(&h.app)["error"].is_null()); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(error.contains(&fallback), "an input error keeps the existing model-preview route"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive_waiting_show_text(&mut h, epoch + 0.06).contains(&fallback)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_after_supported_edit_drops_old_pixels_and_new_capture_still_publishes") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let old = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + assert!(!interactive::awaiting_current_frame(&h.app)); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let document = h.app.session.doc.clone(); + + h.app.render_workspace.view.raytrace.shadows = false; + let text = interactive_waiting_show_text(&mut h, epoch + 0.4); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_cache(&h.app).is_none(), "the previously accepted image must be dropped"); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.41, false, true); + assert!(!painted, "old pixels cannot become current while the new request waits"); + output.textures_delta.clear(); + + let new = interactive_recovery_require_success(&mut h, epoch + 0.901, epoch + 1.0); + assert_ne!(new, old); + assert!(!interactive::awaiting_current_frame(&h.app)); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), new); + assert!(!job.status().unwrap().request.raytrace.as_ref().unwrap().shadows); + assert!(Arc::ptr_eq(&document, &h.app.session.doc), "presentation and runtime settings do not author CAD state"); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_preserves_paused_out_of_date_pixels_and_resume_waits_without_fallback") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.render_workspace.view.raytrace.shadows = true; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let (before, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.shadows = false; + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(painted, "explicit pause still permits the already displayed image"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app)); + let (after, after_samples, after_complete, after_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((after.job, after.png_sha256), (before.job, before.png_sha256)); + assert_eq!((after_samples, after_complete, after_texture), (samples, complete, texture)); + + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let text = interactive_waiting_show_text(&mut h, epoch + 0.5); + assert_eq!(interactive::inspect(&h.app)["phase"], "Updating"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.51, false, true); + assert!(!painted); + output.textures_delta.clear(); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_camera_late_callback_and_document_switch_never_adopt_old_pixels") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.cam.yaw += 0.2; + let text = interactive_waiting_show_text(&mut h, epoch + 0.3); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(!text.contains(h.app.tr("render.error_gpu_preview"))); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::awaiting_current_frame(&h.app)); + interactive_assert_final_export_isolation(&mut h, &held.job); + + let old_uid = h.app.session.uid; + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert_ne!(h.app.session.uid, old_uid); + assert!(!interactive::awaiting_current_frame(&h.app), "a foreign context cannot reserve the canvas even before refresh"); + h.app.ui.tab = "RENDER".into(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.5, false); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.6, false, true); + assert!(!painted, "neither the old image nor its waiting presentation belongs to another document"); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["enabled"], false); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_waiting_canvas_rejects_live_foreign_session_without_resetting_context") { + return; + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::awaiting_current_frame(&h.app)); + let before = interactive::inspect(&h.app); + assert_eq!(before["enabled"], true); + assert_eq!(before["phase"], "Updating"); + assert_eq!(before["paused"], false); + assert!(before["error"].is_null()); + assert!(!h.app.render_workspace.view.result); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + + let uid = h.app.session.uid; + let document = h.app.session.doc.clone(); + let mut foreign = Session::new((*document).clone()); + assert_ne!(foreign.uid, uid); + // Use real engine Sessions and the same ownership swap as documents::swap_in. + // Deliberately omit the UI reset: it would otherwise mask is_current's guard. + // Retain the original Session so its registry/controller lifetime stays live. + std::mem::swap(&mut h.app.session, &mut foreign); + assert_ne!(h.app.session.uid, uid); + assert_eq!(h.app.session.doc, document, "equal design contents do not confer session ownership"); + assert_eq!(interactive::inspect(&h.app), before, "the context is still enabled, not reset or refreshed"); + assert!(active(&h.app)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert!(!h.app.render_workspace.view.result); + assert!(!interactive::awaiting_current_frame(&h.app), "a live context owned by another Session cannot reserve the canvas"); + assert_eq!(interactive::inspect(&h.app), before, "the predicate must remain read-only"); + + std::mem::swap(&mut h.app.session, &mut foreign); + assert_eq!(h.app.session.uid, uid); + assert_eq!(interactive::inspect(&h.app), before); + assert!(interactive::awaiting_current_frame(&h.app), "restoring the real owner proves the same context remained live"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!h.app.render_workspace.interactive.pending()); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_frame(h: &mut Harness, time: &mut f64, events: Vec) { + *time += 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), + time: Some(*time), + focused: true, + events, + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + output.textures_delta.clear(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_fixture(case: &str) -> Option<(Harness, f64, egui::Pos2)> { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, case) { + return None; + } + h.app.run("select.filter", json!({"mode":"body"})).unwrap(); + h.app.run("select.clear", json!({})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + h.app.preferences.nav = "fusion".into(); + h.app.preferences.zoom_to_cursor = false; + h.app.preferences.smooth_wheel_zoom = false; + let mut time = interactive::test_clock(&h.app).as_secs_f64(); + for _ in 0..3 { + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + } + let rect = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, rect); + let at = projection.to_screen(h.app.cam.target).unwrap(); + assert!(!crate::shell::covered(&h.app, at)); + assert!( + crate::viewport::pick(&h.app, &projection, at).iter().any(|hit| matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject")) + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + Some((h, time, at)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn interactive_canvas_input_click(h: &mut Harness, time: &mut f64, at: egui::Pos2, button: egui::PointerButton, mods: egui::Modifiers) { + interactive_canvas_input_frame(h, time, vec![egui::Event::ModifiersChanged(mods), egui::Event::PointerMoved(at)]); + for pressed in [true, false] { + interactive_canvas_input_frame(h, time, vec![egui::Event::PointerButton { pos: at, button, pressed, modifiers: mods }]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_blocks_hover_selection_and_context_but_off_keeps_real_targets") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none(), "hidden geometry cannot advertise a hover target"); + assert!(h.app.session.selection.is_empty(), "plain/add/toggle clicks cannot select invisible geometry"); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none(), "a right click cannot open a menu for hidden geometry"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending(), "show never dispatches a capture"); + + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_some(), "the same real hit remains available with Interactive Off"); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_some(), "the same native canvas click still opens the normal body menu"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work() { + for sampling in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_neither_paints_nor_samples_and_escape_and_off_still_work") + else { + return; + }; + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let look = h.app.render_workspace.view.assign.look.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.assign.look, look, "no hidden face is sampled"); + assert_eq!(h.app.render_workspace.view.assign.sampling, sampling); + assert_eq!(h.app.render_workspace.view.assign.painting, !sampling); + + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + if sampling { + h.app.start("appearance.pick_up"); + } else { + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + if sampling { + assert!(!h.app.render_workspace.view.assign.sampling); + assert!(h.app.render_workspace.view.assign.painting, "Off permits real sampling to arm paint"); + } else { + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clears_real_drag_preview_and_release_cannot_apply_hidden_target") + else { + return; + }; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "positive control: real Off drag reached geometry"); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_current_and_paused_images_keep_canvas_paint_and_final_observation() { + for paused in [false, true] { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_current_and_paused_images_keep_canvas_paint_and_final_observation") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + if paused { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + } + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + let undo = h.app.session.undo.len(); + assign::arm(&mut h.app, json!({"appearance":"ABS - Blue"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.session.doc.appearances.bodies.get("Subject").unwrap().name, "ABS - Blue"); + if paused { + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::awaiting_current_frame(&h.app)); + } else { + assert!(interactive::test_cache(&h.app).is_none(), "the final observation sees the appearance edit made by this canvas click"); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_canvas_reobserves_pending_edit_before_release_and_navigation_still_updates_camera") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + assert!(interactive::test_cache(&h.app).is_some(), "before show, old UI state has not yet observed the visible setting edit"); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(h.app.session.selection.is_empty(), "the release cannot pick using the previous frame's cache/phase"); + assert!(h.app.viewport.hover.is_none()); + + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, 3.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }], + ); + assert_ne!(h.app.cam, camera, "the waiting guard must not swallow real shared camera navigation"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(h.app.viewport.hover.is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "neither observation dispatches Snapshot"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_accepted_image_drag_setting_edit_and_immediate_release_never_applies_hidden_target") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(at)]); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(accepted.job, job); + assert_eq!((samples, complete), (16, true)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert!(!h.app.render_workspace.interactive.pending()); + + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let selection = h.app.session.selection.clone(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Blue"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "the real drag must start over the accepted CPU image"); + assert!(assign::hover(&h.app).is_some()); + let (pressed, pressed_samples, pressed_complete, pressed_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((pressed.job, &pressed.png_sha256), (job, &accepted.png_sha256)); + assert_eq!((pressed_samples, pressed_complete, pressed_texture), (samples, complete, texture)); + assert!(!interactive::awaiting_current_frame(&h.app)); + + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + // No tick, show, refresh, move or other UI frame between this edit and release. + // The old image/drag are still present, so only same-frame observation can reject the drop. + let (before_release, _, _, before_release_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((before_release.job, &before_release.png_sha256, before_release_texture), (job, &accepted.png_sha256, texture)); + assert!(assign::preview(&h.app).is_some()); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(assign::preview(&h.app).is_none()); + assert!(assign::hover(&h.app).is_none()); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert_eq!(h.app.session.selection, selection); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch Snapshot to consume this release"); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "show must not attach a replacement CPU job"); + assert!(active(&h.app)); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + assert!(!assign::cancel(&mut h.app), "the release must consume the drag; nothing may remain for Escape to cancel"); + + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("interactive_blank_canvas_clicks_preserve_selection_created_on_the_accepted_image") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Subject".into() })); + assert!(!interactive::awaiting_current_frame(&h.app)); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + + h.app.render_workspace.view.raytrace.shadows = !h.app.render_workspace.view.raytrace.shadows; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::awaiting_current_frame(&h.app)); + assert!(interactive::test_cache(&h.app).is_none()); + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL] { + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, mods); + assert_eq!(h.app.session.selection, selection, "blank-canvas clicks cannot clear, add to or toggle the existing selection"); + assert!(h.app.viewport.hover.is_none()); + assert!(interactive::awaiting_current_frame(&h.app)); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn gpu_failed_host_keeps_specific_reason_in_image_params_and_disabled_commands() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + for reason in ["This Direct3D 12 session has not tested Vulkan.", "Vulkan device creation failed: deliberate independent diagnostic 47."] { + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_ne!(reason, h.app.tr("render.gpu_unavailable")); + assert_eq!(image_params(&h.app).unwrap_err(), reason); + for id in ["render.preflight", "render.start"] { + let command = solidcraft_engine::find_command(id).unwrap(); + assert!(command.info(&h.app.session).enabled, "the engine must not hide the UI readiness check"); + let info = interactive_command_info(&h.app, command); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(reason), "{id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::GpuRaytrace); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); +} + +#[test] +fn gpu_pending_hosts_keep_generic_disabled_reason_without_starting_setup() { + let mut h = Harness::new(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let generic = h.app.tr("render.gpu_unavailable").to_string(); + // This channel represents a still-pending answer; no worker or GPU factory is created. + let (_sender, receiver) = std::sync::mpsc::channel(); + for host in [PathHost::NotStarted, PathHost::Preparing(receiver, std::time::Instant::now())] { + let preparing = matches!(&host, PathHost::Preparing(..)); + h.app.render_workspace.path_host = host; + assert_eq!(image_params(&h.app).unwrap_err(), generic); + for id in ["render.preflight", "render.start"] { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert!(!info.enabled, "{id}"); + assert_eq!(info.disabled_reason.as_deref(), Some(generic.as_str()), "{id}"); + } + assert_eq!(matches!(&h.app.render_workspace.path_host, PathHost::Preparing(..)), preparing); + assert!(matches!(&h.app.render_workspace.path_host, PathHost::NotStarted | PathHost::Preparing(..))); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[test] +fn gpu_failed_host_preserves_raster_readiness_and_cooperative_cpu_refusal() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":10,"width":12,"height":3})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.render_workspace.image_host = Some(solidcraft_engine::render::job::CpuHost::cooperative()); + sync_backend(&mut h.app); + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + for method in [ImageMethod::Raster, ImageMethod::CpuRaytrace] { + h.app.render_workspace.view.method = method; + h.app.render_workspace.path_host = PathHost::NotStarted; + let baseline = image_params(&h.app); + if method == ImageMethod::Raster { + assert!(baseline.is_ok(), "cooperative Raster must be available: {baseline:?}"); + } else { + assert_eq!(method, ImageMethod::CpuRaytrace); + let error = baseline.as_ref().unwrap_err(); + assert!(error.contains("CPU raytracing"), "cooperative CPU must retain its own host refusal: {error}"); + assert_ne!(error, h.app.tr("render.gpu_unavailable")); + } + let baseline_commands = ["render.preflight", "render.start"].map(|id| { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, method == ImageMethod::Raster, "{method:?}: {id}"); + assert_eq!(info.disabled_reason.as_deref(), baseline.as_ref().err().map(String::as_str), "{method:?}: {id}"); + (id, info.enabled, info.disabled_reason) + }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()); + let reason = "Deliberate GPU-only refusal must not replace another method's readiness."; + h.app.render_workspace.path_host = PathHost::Failed(reason.into()); + assert_eq!(image_params(&h.app), baseline, "{method:?}: preserve the exact success or rejection"); + for (id, enabled, disabled_reason) in baseline_commands { + let info = interactive_command_info(&h.app, solidcraft_engine::find_command(id).unwrap()); + assert_eq!(info.enabled, enabled, "{method:?}: {id}"); + assert_eq!(info.disabled_reason, disabled_reason, "{method:?}: {id}"); + } + assert!(matches!(&h.app.render_workspace.path_host, PathHost::Failed(stored) if stored == reason)); + assert_eq!(h.app.render_workspace.view.method, method); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history); + assert!(h.app.render_workspace.view.job.is_none()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export() { + use solidcraft_engine::render::job::{RectangleLightOptions, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_area_and_led_real_snapshot_pixels_reach_receiver_cache_without_final_export") { + return; + } + h.app.render_workspace.view.raytrace.area_lights = Some(vec![RectangleLightOptions { + center_mm: [5.0, 4.0, 20.0], + edge_u_mm: [4.0, 0.0, 0.0], + edge_v_mm: [0.0, -4.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + }]); + h.app.render_workspace.view.raytrace.area_samples = Some(4); + h.app.render_workspace.view.raytrace.seed = Some(73); + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [0.25, 0.5, 1.0], + intensity: 3.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.draft.exposure_ev = 0.75; + let expected = h.app.render_workspace.view.raytrace.area_lights.clone().unwrap(); + assert_eq!(expected.len(), 2); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + // Existing helper dispatches the real Snapshot, receives its real reply, + // validates real native PNG bytes/hash, drains the reply and paints the cache. + let id = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), id); + let status = job.status().unwrap(); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(options.area_lights.as_ref(), Some(&expected)); + assert_eq!(options.area_samples, Some(4)); + assert_eq!(options.seed, Some(73)); + assert_eq!(options.exposure_ev, 0.75); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + let (cached, samples, complete, _) = interactive::test_cache(&h.app).unwrap(); + let frame = job.frame().unwrap().unwrap(); + assert_eq!((cached.job, cached.png_sha256), (id, frame.info.png_sha256.clone())); + assert_eq!((cached.width, cached.height, samples, complete), (16, 16, 16, true)); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final() { + use solidcraft_engine::render::job::{CpuHost, JobId, Phase, led_strip::LedStripOptions}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_led_light_edit_and_final_preemption_discard_real_late_replies_without_erasing_final") { + return; + } + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + crate::documents::switch(&mut h.app, 0); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + LedStripOptions { + center_mm: [5.0, 4.0, 12.0], + length_mm: 8.0, + width_mm: 1.0, + length_axis: [1.0, 0.0, 0.0], + width_axis: [0.0, -1.0, 0.0], + color: [1.0, 0.5, 0.25], + intensity: 2.0, + } + .append_to(&mut h.app.render_workspace.view.raytrace, 4) + .unwrap(); + h.app.render_workspace.view.raytrace.seed = Some(91); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let first = interactive_hold_real_completed_callback(&mut h); + let old = first.job.id(); + let old_options = first.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(old_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 2.0); + assert_eq!((old_options.area_samples, old_options.seed), (Some(4), Some(91))); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + h.app.render_workspace.view.raytrace.area_lights.as_mut().unwrap().first_mut().unwrap().intensity = 1.5; + interactive_clear_acceptance_frame(&mut h, epoch + 0.3, false); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > visual); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "light edit must detach the old owned job"); + first.sender.send(first.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, false, true); + assert!(!painted); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &first.job); + + interactive_clear_acceptance_frame(&mut h, epoch + 0.601, true); + let second = interactive_hold_real_completed_callback(&mut h); + assert_ne!(second.job.id(), old); + let new_options = second.job.status().unwrap().request.raytrace.unwrap(); + assert_eq!(new_options.area_lights.as_ref().unwrap().first().unwrap().intensity, 1.5); + assert_eq!((new_options.area_samples, new_options.seed), (Some(4), Some(91))); + let final_host = CpuHost::cooperative(); + let final_job = { + let background = h.app.docs.background_mut().next().unwrap(); + background.session.set_render_job_host(Some(final_host.clone())).unwrap(); + let reply = background.session.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + let id: JobId = serde_json::from_value(reply["job"].clone()).unwrap(); + background.session.render_job_handle(id).unwrap() + }; + let retained = final_host.admitted_bytes(); + interactive_clear_acceptance_frame(&mut h, epoch + 0.7, false); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + second.sender.send(second.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.8, false, true); + assert!(!painted, "a final-suspended late LED reply cannot fill the preview cache"); + output.textures_delta.clear(); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::inspect(&h.app)["error"].is_null()); + interactive_assert_final_export_isolation(&mut h, &second.job); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued); + assert_eq!(final_host.admitted_bytes(), retained); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued, "Off cannot cancel the unrelated final"); + final_job.cancel().unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle() { + use solidcraft_engine::render::job::DirectionalLightOptions; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle") { + return; + } + h.app + .run( + "appearance.assign", + json!({"bodies":["Subject"],"color":"#808080","opacity":1.0, + "pbr":{"metallic":0.0,"roughness":1.0,"dielectric_ior":1.0}}), + ) + .unwrap(); + // Front view sees the y=0 face normally. All jittered rays through the + // central pixel stay inside that face, so neither coverage nor noise is an oracle. + h.app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, 4.0, 2.0); + h.app.cam.yaw = 0.0; + h.app.cam.pitch = 0.0; + h.app.cam.roll = 0.0; + h.app.cam.distance = 10.0; + h.app.cam.fov = 0.0; + h.app.cam.up = solidcraft_engine::render::UpAxis::Z; + h.app.render_workspace.view.cpu.environment = cpu::Environment::None; + h.app.render_workspace.view.raytrace = solidcraft_engine::render::job::RaytraceOptions { + lights: Some(vec![DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 0.5 }]), + shadows: false, + ..Default::default() + }; + let camera = h.app.cam; + let final_options = h.app.render_workspace.view.raytrace.clone(); + let final_size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let mut previous_job = None; + let mut baseline_png = None; + let mut previous_visual = None; + for (step, ev) in [0.0_f64, 1.0, -1.0, 0.0].into_iter().enumerate() { + let time = epoch + step as f64; + h.app.render_workspace.view.draft.exposure_ev = ev; + interactive_clear_acceptance_frame(&mut h, time, false); + let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + if let Some(previous) = previous_visual { + assert!(visual > previous, "each committed EV must invalidate the previous image"); + } + previous_visual = Some(visual); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + // This is the real runtime request, not a test-only renderer request. + let wire = interactive_request(&h.app).unwrap(); + assert_eq!(wire["settings"]["exposure_ev"], 0.0, "outer EV must not duplicate the CPU EV"); + assert_eq!(wire["raytrace"]["exposure_ev"], ev); + interactive_clear_acceptance_frame(&mut h, time + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.camera, camera); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, ev, "actual admitted job must carry EV exactly once"); + if let Some(previous) = previous_job { + assert_ne!(held.job.id(), previous, "an EV edit must not reuse the old admitted job"); + } + previous_job = Some(held.job.id()); + let frame = held.job.frame().unwrap().unwrap(); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + // Original closed-form oracle: index-matched opaque dielectric has no + // Fresnel/specular term, so L = IEC-sRGB(128) * 0.5 / pi at normal incidence. + // Apply 2^EV once, Reinhard once, then IEC sRGB once and round to eight bits. + // No renderer BRDF/transfer helper or measured baseline supplies expectations. + let encoded = 128.0_f64 / 255.0; + let albedo = ((encoded + 0.055) / 1.055).powf(2.4); + let exposed = albedo * 0.5 / std::f64::consts::PI * 2.0_f64.powf(ev); + let mapped = exposed / (1.0 + exposed); + let srgb = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; + let expected = (255.0 * srgb).round() as u8; + assert!(expected > 0 && expected < 255, "fixture must stay away from black and clipping"); + assert_eq!(png.get_pixel(7, 7).0, [expected, expected, expected, 255], "EV={ev}: actual native CPU PNG must match analytic radiance"); + if step == 0 { + baseline_png = Some(frame.png().to_vec()); + } else if step == 3 { + assert_eq!(frame.png(), baseline_png.as_ref().unwrap().as_slice(), "EV reversal must return the deterministic original PNG"); + } + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256), (held.job.id(), frame.info.png_sha256.clone())); + assert_eq!((samples, complete), (16, true)); + let uploaded = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + assert_eq!(pixels.size, [16, 16]); + assert_eq!( + pixels.pixels[7 * 16 + 7], + Color32::from_rgb(expected, expected, expected), + "the accepted texture must contain the analytic pixel" + ); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); + assert_eq!(interactive::inspect(&h.app)["stale"], false); + assert_eq!(interactive::inspect(&h.app)["provisional"], true); + interactive_assert_final_export_isolation(&mut h, &held.job); + assert_eq!(h.app.render_workspace.view.raytrace, final_options); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), final_size); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery") { + return; + } + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let original = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); + let original_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let path = h.dir.join("interactive-accepted-to-pending-original.hdr"); + let bytes = original_hdr_bytes(192, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: path.to_string_lossy().into_owned() }; + // Even a real valid file is not admitted until inspected. An already + // displayed CPU frame must disappear, not masquerade as the new HDR intent. + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, true, true); + assert!(!painted); + output.textures_delta.clear(); + let error = interactive_recovery_require_error(&mut h, epoch + 0.5); + assert_eq!(error, h.app.tr("render.hdr_inspect_required")); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > original_visual); + assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); + assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); + // A correcting inspection must respect explicit user pause. Resume then + // captures the actual checked HDR through Snapshot/CPU, rather than falling + // back to the old frame or manufacturing a successful callback. + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); + let checked = interactive_request(&h.app).unwrap(); + { + use sha2::{Digest, Sha256}; + assert_eq!(checked["environment"]["expected_sha256"], format!("{:x}", Sha256::digest(&bytes))); + } + interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); + interactive_clear_acceptance_frame(&mut h, epoch + 1.5, true); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + assert!(interactive::inspect(&h.app)["error"].is_null()); + assert!(!h.app.render_workspace.interactive.pending()); + assert!(interactive::test_current(&h.app).unwrap().is_none()); + assert!(interactive::test_cache(&h.app).is_none(), "the earlier accepted image cannot return after correcting HDR"); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let recovered = interactive_recovery_require_success(&mut h, epoch + 1.701, epoch + 1.8); + assert_ne!(recovered, original); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + assert_eq!(job.id(), recovered); + let frame = job.frame().unwrap().unwrap(); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + assert_eq!((cached.job, samples, complete), (recovered, 16, true)); + assert_eq!(interactive_request(&h.app).unwrap(), checked); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 2.0, true, true); + assert!(painted, "Pause retains the newly recovered actual frame"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["paused"], true); + let (paused, paused_samples, paused_complete, paused_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (paused.job, paused.png_sha256, paused_samples, paused_complete, paused_texture), + (recovered, frame.info.png_sha256.clone(), 16, true, texture) + ); + assert!(!output.textures_delta.set.contains_key(&texture), "Pause reuses the recovered texture"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + assert_eq!(job.frame().unwrap().unwrap().png(), frame.png()); + interactive_assert_final_export_isolation(&mut h, &job); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +fn partial_png_contract_encode(width: u32, height: u32, pixels: Vec) -> Vec { + // Original unit input for the real decoder/receiver, not a CPU render receipt. + let pixels = image::RgbaImage::from_raw(width, height, pixels).unwrap(); + let mut png = std::io::Cursor::new(Vec::new()); + pixels.write_to(&mut png, image::ImageFormat::Png).unwrap(); + png.into_inner() +} + +fn partial_png_contract_request() -> solidcraft_engine::render::job::ImageRequest { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, RaytraceOptions}; + ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + environment: None, + textures: None, + camera: Default::default(), + width: 2, + height: 2, + background: [32, 64, 96], + transparent_background: false, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { progressive: Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 291 }), ..Default::default() }), + } +} + +fn partial_png_contract_info(png: &[u8]) -> solidcraft_engine::render::job::PartialPreviewInfo { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::{ + ExecutorId, + job::{AlphaConvention, ColourEncoding, FrameInfo, JobId, PartialPreviewInfo, PartialPreviewProjection}, + }; + // Synthetic descriptor for pure contract tests. No Host/JobHandle, capture, + // native executor or final registry is installed or claimed by this helper. + PartialPreviewInfo { + frame: FrameInfo { + job: JobId { session: 100, serial: 1, generation: 1 }, + scene_generation: 7, + backend: solidcraft_engine::render::builtin_backend().id, + executor: ExecutorId::new("cpu-raytrace").unwrap(), + width: 2, + height: 2, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: png.len() as u64, + png_sha256: format!("{:x}", Sha256::digest(png)), + }, + sequence: 1, + source_width: 2, + source_height: 2, + completed_passes: 0, + updated_prefix: 3, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + } +} + +#[test] +fn partial_png_contract_four_pixels_separate_hit_miss_black_and_unknown() { + let request = partial_png_contract_request(); + // Independently derived IEC/Reinhard bytes for linear(.25,.5,1) at EV0: + // encode(1/5), encode(1/3), encode(1/2) = (124,156,188). + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 8192).unwrap(); + assert_eq!(decoded.pixels, vec![Color32::from_rgb(124, 156, 188), Color32::from_rgb(32, 64, 96), Color32::BLACK, Color32::TRANSPARENT,]); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 3); + assert!(sampling.source_unknown(), "global Unknown drives the added geometry gate"); + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(0, 1, Color32::TRANSPARENT, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 0, Color32::BLACK, request.background).is_err()); + assert!(interactive::validate_partial_pixel(1, 1, Color32::BLACK, request.background).is_ok()); +} + +#[test] +fn partial_png_contract_second_prefix_keeps_nonuniform_counts_and_resolved_coverage() { + let request = partial_png_contract_request(); + // Original second-prefix source means are(.5,.25,1) and(0,1,0). + // The second has C/N=.5, so covered green2 is mapped BEFORE coverage: + // linear(.5*decode8(32), 1/3+.5*decode8(64), .5*decode8(96)), + // encoded once = (20,162,68). These PNG inputs must never be regraded by UI. + let png = partial_png_contract_encode(2, 2, vec![156, 124, 188, 255, 20, 162, 68, 255, 0, 0, 0, 255, 32, 64, 96, 255]); + let mut info = partial_png_contract_info(&png); + info.sequence = 2; + info.completed_passes = 1; + info.updated_prefix = 2; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[2, 1, 1, 0], sampling, 8192).unwrap(); + assert_eq!( + decoded.pixels, + vec![Color32::from_rgb(156, 124, 188), Color32::from_rgb(20, 162, 68), Color32::BLACK, Color32::from_rgb(32, 64, 96),] + ); + let counts: Vec<_> = (0..4).map(|index| interactive::partial_sample_count(1, 2, index, 4, 16).unwrap()).collect(); + assert_eq!(counts, vec![2, 2, 1, 1]); + assert_eq!(sampling.sample_range(), (1, 2), "this is not uniform2SPP"); + assert_eq!(sampling.sampled_source_pixels(), 4); + assert!(!sampling.source_unknown(), "only the additional Unknown block ends; all M3 gates still apply"); +} + +#[test] +fn partial_png_contract_frontier_bounds_keep_full_pass_sentinel_and_never_wrap() { + for index in 0..4 { + assert_eq!(interactive::partial_sample_count(0, 0, index, 4, 16).unwrap(), 0); + assert_eq!(interactive::partial_sample_count(1, 0, index, 4, 16).unwrap(), 1); + assert_eq!(interactive::partial_sample_count(16, 0, index, 4, 16).unwrap(), 16); + } + for (s, k, i, p, target) in [ + (0, 4, 0, 4, 16), + (0, 0, 4, 4, 16), + (0, 0, u64::MAX, 4, 16), + (0, 0, 0, 0, 16), + (0, 0, 0, 4, 0), + (17, 0, 0, 4, 16), + (16, 1, 0, 4, 16), + (u32::MAX, 1, 0, 4, u32::MAX), + ] { + assert!(interactive::partial_sample_count(s, k, i, p, target).is_err()); + } +} + +#[test] +fn partial_png_contract_rejects_high_invalid_identity_without_burning_accepted_sequence() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let accepted = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::validate_partial_metadata(&expected, &info, png.len(), 4, Some(accepted)).unwrap().is_none()); + let mut invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.job.generation += 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.frame.width = 1; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; + invalid.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + invalid = info.clone(); + invalid.sequence = 99; // advancing sequence with unchanged frontier is not new work + assert!(interactive::validate_partial_metadata(&expected, &invalid, png.len(), 4, Some(accepted)).is_err()); + let mut next = info.clone(); + next.sequence = 2; // legitimate lower-than-rejected99 publication + next.completed_passes = 1; + next.updated_prefix = 2; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).unwrap().is_some()); + next.sequence = 0; + assert!(interactive::validate_partial_metadata(&expected, &next, png.len(), 4, Some(accepted)).is_err()); +} + +#[test] +fn partial_png_contract_decoder_refuses_unknown_blur_coverage_and_malformed_png() { + let request = partial_png_contract_request(); + let png = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 255, 0, 0, 0, 255, 0, 0, 0, 0]); + let info = partial_png_contract_info(&png); + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2, 2] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 4, None).unwrap().unwrap(); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 0], sampling, 1).is_err(), "no implicit Triangle resize of Unknown"); + assert!(interactive::decode_partial_image(&request, &info, b"not a PNG", &[1, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1, 1], sampling, 8192).is_err(), "Unknown has no covered sample"); + assert!(interactive::decode_partial_image(&request, &info, &png, &[2, 0, 1, 0], sampling, 8192).is_err()); + assert!(interactive::decode_partial_image(&request, &info, &png, &[1, 0, 1], sampling, 8192).is_err()); + let bad_alpha = partial_png_contract_encode(2, 2, vec![124, 156, 188, 255, 32, 64, 96, 128, 0, 0, 0, 255, 0, 0, 0, 0]); + let bad_info = partial_png_contract_info(&bad_alpha); + let bad_sampling = interactive::validate_partial_metadata(&expected, &bad_info, bad_alpha.len(), 4, None).unwrap().unwrap(); + assert!( + interactive::decode_partial_image(&request, &bad_info, &bad_alpha, &[1, 0, 1, 0], bad_sampling, 8192).is_err(), + "metadata admitted; sampled physical coverage must already be opaque" + ); +} + +#[test] +fn partial_png_contract_shared_plan_keeps_unrepresented_unknown_globally_blocked() { + use sha2::{Digest, Sha256}; + let mut request = partial_png_contract_request(); + request.width = 2048; + request.height = 1; + let png = partial_png_contract_encode(1024, 1, [0, 0, 0, 255].repeat(1024)); + let mut info = partial_png_contract_info(&png); + info.source_width = 2048; + info.source_height = 1; + info.frame.width = 1024; + info.frame.height = 1; + info.frame.png_bytes = png.len() as u64; + info.frame.png_sha256 = format!("{:x}", Sha256::digest(&png)); + info.updated_prefix = 2047; + let expected = interactive::PartialExpectation { job: info.frame.job, scene_generation: 7, request: &request, final_dimensions: [2048, 1] }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), 1024, None).unwrap().unwrap(); + let decoded = interactive::decode_partial_image(&request, &info, &png, &[1; 1024], sampling, 8192).unwrap(); + assert!(decoded.pixels.iter().all(|pixel| *pixel == Color32::BLACK)); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 2047); + assert!(sampling.source_unknown(), "all1024 representatives known does not observe source pixel2047"); + let plan = solidcraft_engine::render::job::PartialPreviewPlan::new(2048, 1).unwrap(); + assert_eq!(plan.source_index(0).unwrap(), 0); + assert_eq!(plan.source_index(1023).unwrap(), 2046); + assert!(plan.source_index(1024).is_err()); +} + +#[test] +fn partial_png_contract_egui_clock_throttles_attempts_without_wall_time_or_fake_frames() { + use solidcraft_engine::render::job::JobId; + use std::time::Duration; + let job = JobId { session: 100, serial: 1, generation: 1 }; + assert!(interactive::partial_request_due(None, job, Duration::ZERO)); + let first = Some((job, Duration::ZERO)); // caller records every attempt, including false + assert!(!interactive::partial_request_due(first, job, Duration::from_millis(249))); + assert!(interactive::partial_request_due(first, job, Duration::from_millis(250))); + let second = Some((job, Duration::from_millis(250))); + assert!(!interactive::partial_request_due(second, job, Duration::from_millis(499))); + assert!(interactive::partial_request_due(second, job, Duration::from_millis(500))); + let mut newer = job; + newer.serial += 1; + assert!(interactive::partial_request_due(second, newer, Duration::from_millis(251))); + let clock = interactive::monotonic(Duration::from_millis(500), 0.499); + assert_eq!(clock, Duration::from_millis(500)); + assert!(!interactive::partial_request_due(Some((job, clock)), job, Duration::from_millis(499))); +} + +#[test] +fn partial_frame_visibility_paused_unknown_yields_to_final_priority() { + use interactive::FrameVisibility; + // Policy inputs only: no Host/JobHandle, fake CPU output or native receipt. + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + assert!(paused.paintable(), "normal M3 paused/stale image remains visible"); + assert!(paused.blocks_unknown(true), "source Unknown still blocks geometry while paused"); + assert!(!paused.blocks_unknown(false), "known source does not gain an extra gate"); + let preempted = FrameVisibility { final_active: true, ..paused }; + assert!(!preempted.paintable()); + assert!(!preempted.blocks_unknown(true), "an image hidden by a manual final cannot reserve the Model canvas"); + // This is the nonwaiting case: both production paint and the Unknown arm + // decline it, so the existing parent can reach its visible Raster fallback. +} + +#[test] +fn partial_frame_visibility_error_or_missing_texture_cannot_claim_unknown_canvas() { + use interactive::FrameVisibility; + let paused = FrameVisibility { + has_context: true, + final_active: false, + has_error: false, + paused: true, + stale: true, + revision_matches: false, + texture_ok: true, + }; + for hidden in [ + FrameVisibility { has_error: true, ..paused }, + FrameVisibility { texture_ok: false, ..paused }, + FrameVisibility { has_context: false, ..paused }, + FrameVisibility { paused: false, ..paused }, + ] { + assert!(!hidden.paintable()); + assert!(!hidden.blocks_unknown(true), "hidden pixels cannot suppress visible Raster or its geometry targets"); + } + let current = FrameVisibility { paused: false, stale: false, revision_matches: true, ..paused }; + assert!(current.paintable()); + assert!(current.blocks_unknown(true), "all-known representatives cannot erase global source Unknown"); + assert!(!FrameVisibility { stale: true, ..current }.blocks_unknown(true)); + assert!(!FrameVisibility { revision_matches: false, ..current }.blocks_unknown(true)); + // Existing waiting/input-cleanup regressions stay in the untouched222 prefix. + // The production awaiting_current_frame arm is not gated by this predicate. +} + +mod cpu_optical_material_routing { + use super::*; + + fn bind_recipe(h: &mut Harness, name: &str, recipe: &str, boundary: materials::Boundary) { + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == name).unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.glass = materials::Glass::recipe(recipe).unwrap(); + // These represent explicit author actions, not a converter's guesses. + binding.glass.boundary = boundary; + binding.cpu_optics = true; + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + } + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"center":[0,0,2],"body_name":"Optics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.render_workspace.view.raytrace.lights = Some(vec![]); + h.app.render_workspace.view.raytrace.shadows = false; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [1.0; 3]; + h.app.render_workspace.view.cpu.intensity = 1.0; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.background = [255; 3]; + h.app.cam = Camera { distance: 50.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + h.app.session.mark_saved(); + h + } + + fn wire(h: &Harness) -> Value { + runtime_image_request(&h.app, false).unwrap() + } + + fn directional_shadow_fixture(choices: &[bool]) -> Harness { + use solidcraft_engine::render::job::DirectionalLightOptions; + assert!(!choices.is_empty() && choices.len() <= 2); + let mut h = Harness::new(); + for index in 0..choices.len() { + h.app + .run("solid.box", json!({"length":2,"width":2,"height":2,"center":[index as f64 * 4.0,0,2],"body_name":format!("Shadow{index}")})) + .unwrap(); + } + h.app.run("render.scene", json!({})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.shadows = true; + h.app.render_workspace.view.raytrace.lights = + Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0, 0.5, 0.25], intensity: 2.0 }]); + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.materials.enabled = true; + let targets = materials::read_targets(&mut h.app).unwrap(); + for (index, shadows) in choices.iter().copied().enumerate() { + let target = targets.iter().find(|target| target.name == format!("Shadow{index}")).unwrap().clone(); + let mut binding = materials::Binding::new(target, &h.app); + binding.cpu_optics = true; + binding.glass_enabled = true; + binding.glass.boundary = materials::Boundary::Box; + binding.glass.shadows = shadows; + h.app.render_workspace.view.materials.bindings.push(binding); + } + h.app.session.mark_saved(); + h + } + + fn directional_shadow_refusal_is_atomic(h: &Harness, key: Option<&str>) { + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"preserve"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let options = json!(h.app.render_workspace.view.raytrace); + let error = materials::params(&h.app, &mut request).unwrap_err(); + if let Some(key) = key { + assert!(error.contains(h.app.tr(key)), "{key}: {error}"); + } + assert_eq!(request, before); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert_eq!(json!(h.app.render_workspace.view.raytrace), options); + } + + #[test] + fn cpu_directional_shadow_uniform_assignments_lower_typed_wire_without_changing_authored_options() { + use solidcraft_engine::render::job::{CpuDielectricTransport, CpuProgressiveOptions, RaytraceOptions}; + for shadows in [false, true] { + for progressive in [false, true] { + for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] { + let mut h = directional_shadow_fixture(&[shadows, shadows]); + h.app.render_workspace.view.raytrace.dielectric_transport = policy; + h.app.render_workspace.view.raytrace.progressive = + progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 }); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials); + let mut expected = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut expected).unwrap(); + let request = runtime_image_request(&h.app, false).unwrap(); + let mut options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + options.validate().unwrap(); + assert_eq!(options.directional_shadow_transmission, shadows); + assert!(options.shadows); + assert_eq!(options.dielectrics.len(), 2); + assert_eq!(options.dielectric_transport, policy); + assert_eq!(options.progressive, h.app.render_workspace.view.raytrace.progressive); + assert!(options.dielectrics.iter().all(|body| body.ior == 1.5 && body.absorption_per_mm == [0.0; 3])); + assert!(request["raytrace"]["dielectrics"].as_array().unwrap().iter().all(|body| body.get("shadow_transmission").is_none())); + if !shadows { + assert!(request["raytrace"].get("directional_shadow_transmission").is_none()); + } + options.dielectrics.clear(); + options.directional_shadow_transmission = false; + assert_eq!(json!(options), expected["raytrace"], "no other CPU option may change"); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), authored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + } + } + } + } + + #[test] + fn cpu_directional_shadow_mixed_body_choices_refuse_both_orders_without_erasing_off() { + for choices in [[false, true], [true, false]] { + let h = directional_shadow_fixture(&choices); + directional_shadow_refusal_is_atomic(&h, Some("render.cpu_shadow_mixed")); + } + } + + #[test] + fn cpu_directional_shadow_all_on_keeps_global_shadows_environment_nesting_and_light_refusals() { + for case in ["global_off", "constant", "hdr", "nested", "reflections", "punctual", "area"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "global_off" => h.app.render_workspace.view.raytrace.shadows = false, + "constant" => h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant, + "hdr" => { + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-shadow-adapter.hdr"); + } + "nested" => h.app.render_workspace.view.cpu.nested_media = true, + "reflections" => h.app.render_workspace.view.raytrace.reflections = Some(Default::default()), + "punctual" => { + h.app.render_workspace.view.raytrace.punctual_lights = Some( + serde_json::from_value(json!([{ + "position_mm":[0,0,100],"color":[1,1,1],"intensity":2,"reference_distance_mm":100,"minimum_distance_mm":0.01 + }])) + .unwrap(), + ); + } + "area" => { + h.app.render_workspace.view.raytrace.area_lights = Some( + serde_json::from_value(json!([{ + "center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3 + }])) + .unwrap(), + ); + } + _ => unreachable!(), + } + h.app.render_workspace.view.raytrace.validate().unwrap(); + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_all_on_preserves_identity_permission_duplicate_and_boundary_gates() { + for case in ["stale", "duplicate", "closed", "permission"] { + let mut h = directional_shadow_fixture(&[true, true]); + match case { + "stale" => { + h.app.run("appearance.assign", json!({"bodies":["Shadow0"],"color":"#123456"})).unwrap(); + } + "duplicate" => { + let duplicate = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(duplicate); + } + "closed" => h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Closed, + "permission" => h.app.render_workspace.view.materials.bindings[0].cpu_optics = false, + _ => unreachable!(), + } + directional_shadow_refusal_is_atomic(&h, None); + } + } + + #[test] + fn cpu_directional_shadow_inactive_off_body_is_not_selected_for_transmission() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.bindings[1].enabled = false; + let request = runtime_image_request(&h.app, false).unwrap(); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert!(options.directional_shadow_transmission); + assert_eq!(options.dielectrics.len(), 1); + assert_eq!(options.dielectrics[0].body_name, "Shadow0"); + assert!(!h.app.render_workspace.view.materials.bindings[1].glass.shadows); + assert!(!h.app.render_workspace.view.materials.bindings[1].enabled); + } + + #[test] + fn cpu_directional_shadow_default_false_and_conflicting_global_intent_are_preserved() { + use solidcraft_engine::render::job::RaytraceOptions; + assert!(!RaytraceOptions::default().directional_shadow_transmission); + assert!(json!(RaytraceOptions::default()).get("directional_shadow_transmission").is_none()); + let h = directional_shadow_fixture(&[false, false]); + let mut request = json!({"settings":{"exposure_ev":1.25},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + request["raytrace"]["directional_shadow_transmission"] = json!(true); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_shadow_conflict"))); + assert_eq!(request, before); + assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission); + let mut h = directional_shadow_fixture(&[true, false]); + h.app.render_workspace.view.materials.enabled = false; + let before = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + assert_eq!(request, before, "disabled materials do not rewrite an unrelated request"); + } + + #[test] + fn cpu_directional_shadow_adapter_messages_are_delivered_in_nine_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in ["render.cpu_directional_shadow_help", "render.cpu_shadow_conflict", "render.cpu_shadow_mixed"] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + #[test] + fn explicit_cpu_recipe_builds_typed_optics_with_independent_linear_units_and_no_design_edit() { + use solidcraft_engine::render::{ + job::{DielectricBoundary, RaytraceOptions}, + transmission::Transmission, + }; + let h = fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); + let request = wire(&h); + let options: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(options.dielectrics.len(), 1); + let material = &options.dielectrics[0]; + assert_eq!((material.body_index, material.body_name.as_str()), (0, "Optics")); + assert_eq!(material.boundary, DielectricBoundary::ClosedBox); + assert_eq!(material.ior, 1.5); + assert_eq!(material.thickness_mm, 0.0); + let [r, g, b] = material.absorption_per_mm; + assert!((r - 0.005050676829379866).abs() < 1e-15); + assert!((g - 0.0025125839633753626).abs() < 1e-15); + assert_eq!(b, 0.0); + // This tests coefficient lowering only. Native pixel tests below test transport. + let medium = Transmission::new(solidcraft_engine::geom::Vec3::new(r, g, b), None).unwrap(); + for (distance, expected) in [(4.0, [0.98, 0.99, 1.0]), (8.0, [0.9604, 0.9801, 1.0])] { + let t = medium.attenuation(distance).unwrap(); + for (actual, expected) in [t.x, t.y, t.z].into_iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12); + } + } + assert!(request["raytrace"].get("clear_coats").is_none()); + assert!(request["raytrace"].get("textures").is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty())); + assert!(setups::snapshot(&h.app).is_err(), "transient CPU optics are not portable GPU saved optics"); + } + + #[test] + fn legacy_gpu_binding_and_closed_recipe_still_need_explicit_cpu_route_and_box_choice() { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = false; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_explicit"))); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_boundary"))); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let mut gpu = json!({}); + materials::params(&h.app, &mut gpu).unwrap(); + assert_eq!(gpu["raytrace"]["dielectrics"][0]["boundary"], "closed_mesh"); + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(materials::params(&h.app, &mut json!({})).is_err()); + } + + #[test] + fn thin_recipe_preserves_authored_shadow_intent_until_explicit_edit() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].glass = materials::Glass::recipe("starter.glass.thin-clear").unwrap(); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_unsupported"))); + assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows); + // User deliberately disables the distinct GPU transmitted-shadow approximation. + h.app.render_workspace.view.materials.bindings[0].glass.shadows = false; + let request = wire(&h); + assert_eq!(request["raytrace"]["dielectrics"][0]["boundary"], "thin_sheet"); + assert_eq!(request["raytrace"]["dielectrics"][0]["thickness_mm"], 2.0); + assert!(request["raytrace"]["dielectrics"][0].get("shadow_transmission").is_none()); + // The box fixture is NOT a certified thin surface; native admission must refuse below. + } + + #[test] + fn unsupported_optical_intent_refuses_atomically_instead_of_erasing_flags_or_maps() { + for case in ["coat", "maps", "shadows", "subsurface", "no_glass"] { + let mut h = fixture(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + match case { + "coat" => binding.coat_enabled = true, + "maps" => { + binding.maps_enabled = true; + binding.maps.normal = "authored-normal.png".into(); + } + "shadows" => binding.glass.shadows = true, + "subsurface" => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => { + binding.glass_enabled = false; + binding.coat_enabled = true; + } + } + let intent = format!("{:?}", h.app.render_workspace.view.materials); + let mut request = json!({"settings":{"exposure_ev":0},"sentinel":"retain"}); + cpu::params(&h.app, &mut request).unwrap(); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).is_err(), "{case}"); + assert_eq!(request, before, "failed lowering must not partially replace CPU options: {case}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), intent, "{case}"); + } + } + + #[test] + fn cpu_optical_request_preserves_hdr_and_all_preexisting_cpu_numeric_options() { + use solidcraft_engine::render::job::RaytraceOptions; + let mut h = fixture(); + h.app.render_workspace.view.raytrace = serde_json::from_value(json!({ + "budget":"studio","primary_samples":4,"shadows":true, + "lights":[{"direction":[0,0,1],"color":[1,0.5,0.25],"intensity":2}], + "punctual_lights":[{"position_mm":[0,0,100],"color":[0.25,0.5,1],"intensity":4, + "reference_distance_mm":100,"minimum_distance_mm":0.01,"cone":{"emitted_axis":[0,0,-1],"inner_half_angle_radians":0.1,"outer_half_angle_radians":0.2}}], + "area_lights":[{"center_mm":[0,0,20],"edge_u_mm":[4,0,0],"edge_v_mm":[0,3,0],"color":[1,1,1],"intensity":3}], + "area_samples":16,"seed":42 + })).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input("not-read-by-optical-ui.hdr"); + h.app.render_workspace.view.cpu.rotation_rad = 0.75; + h.app.render_workspace.view.cpu.intensity = 2.0; + h.app.render_workspace.view.cpu.samples = 64; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + let base = json!(h.app.render_workspace.view.raytrace); + let mut request = json!({"settings":{"exposure_ev":1.25}}); + cpu::params(&h.app, &mut request).unwrap(); + let cpu_request = request.clone(); + materials::params(&h.app, &mut request).unwrap(); + let mut decoded: RaytraceOptions = serde_json::from_value(request["raytrace"].clone()).unwrap(); + assert_eq!(decoded.dielectrics.len(), 1); + decoded.dielectrics.clear(); + assert_eq!(json!(decoded), cpu_request["raytrace"], "only typed dielectrics may change"); + assert_eq!(request["environment"], cpu_request["environment"]); + assert_eq!(request["environment"]["path"], "not-read-by-optical-ui.hdr"); + assert_eq!(request["settings"]["exposure_ev"], 0.0); + assert_eq!(request["raytrace"]["exposure_ev"], 1.25); + assert_eq!(json!(h.app.render_workspace.view.raytrace), base); + } + + #[test] + fn optical_binding_refuses_hidden_changed_ordinal_wrong_feature_and_wrong_document() { + let mut h = fixture(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(runtime_image_request(&h.app, false).is_err(), "visibility need not change revision"); + h.app.session.visibility.hidden_bodies.clear(); + assert!(runtime_image_request(&h.app, false).is_ok()); + h.app.render_workspace.view.materials.bindings[0].target.ordinal = 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().feature += 1; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.render_workspace.view.materials.bindings[0].target.stable_target.as_mut().unwrap().occurrence_path = vec![999]; + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + let document = h.app.session.doc.clone(); + h.app.session.doc = Arc::new((*document).clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "same numerical revision is not same document"); + } + + #[test] + fn optical_revalidation_is_explicit_and_same_body_only() { + let mut h = fixture(); + let mut original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + materials::revalidate(&mut h.app, &mut original).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + assert!(runtime_image_request(&h.app, false).is_ok()); + original.target.name = "Same name is insufficient".into(); + assert!(materials::revalidate(&mut h.app, &mut original).is_err()); + assert_eq!(original.target.name, "Same name is insufficient"); + } + + #[test] + fn optical_limits_duplicates_and_hostile_coefficients_keep_original_request_intact() { + let mut h = fixture(); + for bad in [f64::NAN, f64::INFINITY, -1.0, 3.01] { + h.app.render_workspace.view.materials.bindings[0].glass.ior = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.ior = 1.5; + for bad in [f64::NAN, f64::INFINITY, -0.1, 100.01] { + h.app.render_workspace.view.materials.bindings[0].glass.absorption[0] = bad; + assert!(runtime_image_request(&h.app, false).is_err()); + } + h.app.render_workspace.view.materials.bindings[0].glass.absorption = [0.0; 3]; + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings.push(original.clone()); + assert!(runtime_image_request(&h.app, false).is_err(), "duplicate target is not two media"); + h.app.render_workspace.view.materials.bindings = vec![original; 9]; + assert!(runtime_image_request(&h.app, false).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn progressive_optics_preserves_identity_and_saved_gpu_conflicts_without_mutation() { + let mut h = fixture(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let authored = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + h.app.render_workspace.view.raytrace.progressive = Some(Default::default()); + let progressive_final = runtime_image_request(&h.app, false).unwrap(); + let final_options: RaytraceOptions = serde_json::from_value(progressive_final["raytrace"].clone()).unwrap(); + final_options.validate().unwrap(); + assert_eq!(final_options.primary_samples, 1); + assert_eq!(final_options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(final_options.progressive.unwrap().seed, 0); + let optics = progressive_final["raytrace"]["dielectrics"].clone(); + assert_eq!(optics.as_array().unwrap().len(), 1); + assert_eq!(optics[0]["body_name"], "Optics"); + assert_eq!(optics[0]["boundary"], "closed_box"); + assert_eq!(optics[0]["ior"], 1.5); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + let from_progressive = interactive_request(&h.app).unwrap(); + assert_eq!(from_progressive["raytrace"]["dielectrics"], optics, "preview conversion cannot erase or replace the authored optical material"); + assert!(h.app.render_workspace.view.materials.bindings[0].glass_enabled); + h.app.render_workspace.view.raytrace.progressive = None; + let from_fixed = interactive_request(&h.app).unwrap(); + assert_eq!(from_fixed["raytrace"]["dielectrics"], optics, "Fixed editor preview still carries certified optics"); + let progressive_input: RaytraceOptions = serde_json::from_value(from_progressive["raytrace"].clone()).unwrap(); + progressive_input.validate().unwrap(); + assert_eq!(progressive_input.primary_samples, 1); + assert_eq!(progressive_input.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(progressive_input.progressive.unwrap().seed, 0); + let fixed_input: RaytraceOptions = serde_json::from_value(from_fixed["raytrace"].clone()).unwrap(); + fixed_input.validate().unwrap(); + assert_eq!(fixed_input.primary_samples, 1); + assert!(fixed_input.progressive.is_none(), "the UI Fixed DTO stays Fixed until the engine preview conversion"); + assert!(h.app.render_workspace.view.raytrace.progressive.is_none(), "constructing preview intent cannot change the manual-final editor"); + #[cfg(not(target_arch = "wasm32"))] + if native_host(&mut h, "progressive_bridge_obsolete_guard_adaptation") { + use solidcraft_engine::render::job::{JobId, Phase, interactive::VisualRevision}; + use std::time::Duration; + // Same original20x20/one-pixel/50-distance inputs: this is actual + // capture/admission/completion, not a Beer pixel oracle (jitter may miss). + let mut final_params = progressive_final.clone(); + final_params["progressive_feedback"] = json!(true); + let checked = h.app.run("render.preflight", final_params.clone()).unwrap(); + let started = h.app.run("render.start", final_params).unwrap(); + let final_id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let final_job = h.app.session.render_job_handle(final_id).unwrap(); + let final_status = final_job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error); + assert_eq!(serde_json::to_value(&final_status.request).unwrap(), checked["request"]); + assert_eq!(json!(final_status.request.raytrace), progressive_final["raytrace"]); + assert!(!final_status.options.nested_media); + assert!(final_job.protected_preview_report().unwrap().is_some()); + let final_bytes = final_job.frame().unwrap().unwrap().png().to_vec(); + for (index, params) in [&from_progressive, &from_fixed].into_iter().enumerate() { + let context = h.app.session.interactive_render().unwrap(); + context + .enable(VisualRevision { scene_generation: h.app.session.revision, visual_revision: index as u64 + 1 }, Duration::ZERO) + .unwrap(); + let ticket = context.capture(Duration::from_millis(200)).unwrap().unwrap(); + let snapshot = context.snapshot(&h.app.session, ticket, params).unwrap(); + assert!(snapshot.run().unwrap(), "real optical snapshot must be admitted/adopted"); + let job = context.current().unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + let options = status.request.raytrace.as_ref().unwrap(); + assert_eq!(serde_json::to_value(&options.dielectrics).unwrap(), optics); + assert_eq!(options.primary_samples, 1); + assert_eq!(options.progressive.unwrap().samples_per_pixel, 16); + assert_eq!(options.progressive.unwrap().seed, 0); + assert_eq!((status.request.width, status.request.height), (1, 1)); + assert!(!status.options.nested_media); + assert_eq!(job.id(), ticket.job_id()); + assert!(job.frame().unwrap().is_some()); + assert!(h.app.session.render_job_handle(job.id()).is_err(), "Interactive keeps a separate non-export owner"); + context.disable().unwrap(); + assert_eq!(h.app.session.render_job_handle(final_id).unwrap().frame().unwrap().unwrap().png(), final_bytes.as_slice()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), authored); + let mut request = wire(&h); + let before = request.clone(); + assert!(materials::params(&h.app, &mut request).unwrap_err().contains(h.app.tr("render.cpu_optics_conflict"))); + assert_eq!(request, before); + let target = h.app.render_workspace.view.materials.bindings[0].target.stable_target.clone().unwrap(); + h.app + .render_workspace + .view + .draft + .optics + .set( + solidcraft_engine::doc::render_optics::SavedOptics { + target, + optics: solidcraft_engine::doc::render_optics::OpticalMaterial { + ior: 1.5, + absorption_per_mm: [0.0; 3], + boundary: solidcraft_engine::doc::render_optics::OpticalBoundary::ClosedMesh, + thickness_mm: 0.0, + shadow_transmission: false, + subsurface: None, + }, + }, + false, + ) + .unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + assert_eq!(h.app.render_workspace.view.draft.optics.len(), 1); + } + + #[test] + fn nested_cpu_route_is_an_explicit_cpu_choice_independent_of_gpu_legacy_state() { + let mut h = fixture(); + h.app.render_workspace.view.studio.nested_media = true; + assert_eq!(wire(&h)["nested_media"], false); + h.app.render_workspace.view.cpu.nested_media = true; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.studio.nested_media = false; + assert_eq!(wire(&h)["nested_media"], true); + h.app.render_workspace.view.cpu.nested_media = false; + assert_eq!(wire(&h)["nested_media"], false); + } + + #[cfg(not(target_arch = "wasm32"))] + fn native_host(h: &mut Harness, case: &str) -> bool { + use solidcraft_engine::render::job::CpuHost; + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == solidcraft_engine::render::job::HostKind::NativeWorker + && host.is_available() + && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + if !available { + let request = wire(h); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", request.clone()).is_err()); + assert!(h.app.run("render.start", request).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return false; + } + eprintln!("CPU_OPTICS_BRANCH case={case} cpu_supported=true"); + true + } + + #[cfg(not(target_arch = "wasm32"))] + fn check_start_pixel(h: &mut Harness, expected: [u8; 4]) { + use solidcraft_engine::render::job::{JobId, Phase}; + let request = image_params(&h.app).unwrap(); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); + assert_eq!(checked["request"]["raytrace"]["dielectrics"], request["raytrace"]["dielectrics"]); + assert_eq!(image_params(&h.app).unwrap(), request, "Check and Start must capture identical optical intent"); + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert_eq!(status.options.nested_media, request["nested_media"].as_bool().unwrap()); + let frame = handle.frame().unwrap().unwrap(); + let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(*image.get_pixel(0, 0), image::Rgba(expected)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_box_reaches_same_cpu_check_start_and_real_beer_pixels() { + let mut h = fixture(); + if !native_host(&mut h, "library_box") { + return; + } + // Explicit author edit isolates Beer: index-matched boundaries have zero + // Fresnel reflection, 4 mm actual distance yields [.98,.99,1]. + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.ior = 1.0; + glass.recipe = None; + check_start_pixel(&mut h, [187, 187, 188, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_admission_preserves_opacity_and_refuses_false_thin_certificate() { + let mut h = fixture(); + if !native_host(&mut h, "opacity_and_certificate") { + return; + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Thin; + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "twelve triangles are not a thin-sheet certificate"); + } + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#a0c0e0","opacity":0.25})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].opacity, 0.25); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_thin_library_recipe_uses_actual_imported_planar_certificate_and_virtual_distance() { + let mut h = fixture(); + if !native_host(&mut h, "library_thin") { + return; + } + let path = h.dir.join("original-optical-sheet.stl"); + // Original one-triangle geometry, not a box proxy or commercial fixture. + std::fs::write(&path, b"solid OriginalSheet\nfacet normal 0 0 1\nouter loop\nvertex -20 -20 2\nvertex 20 -20 2\nvertex 0 20 2\nendloop\nendfacet\nendsolid OriginalSheet\n").unwrap(); + h.app.run("file.insert_mesh", json!({"path":path,"name":"OriginalSheet"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + let targets = materials::read_targets(&mut h.app).unwrap(); + assert_eq!(targets.len(), 1); + let name = targets[0].name.clone(); + bind_recipe(&mut h, &name, "starter.glass.thin-clear", materials::Boundary::Thin); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "do not silently delete the recipe's shadow intent"); + glass.shadows = false; // explicit compatible user policy + glass.ior = 1.0; // explicit index-matched Beer experiment + glass.recipe = None; + assert_eq!(solidcraft_engine::product_scene::extract(&h.app.session).unwrap().meshes[0].mesh.triangles.len(), 1); + // 2 mm virtual normal distance -> [.95,.98,.99]; Reinhard+sRGB bytes. + check_start_pixel(&mut h, [185, 187, 187, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_library_nested_opt_in_preserves_real_child_medium_and_default_refusal() { + let mut h = fixture(); + if !native_host(&mut h, "library_nested") { + return; + } + h.app.run("solid.box", json!({"length":10,"width":10,"height":2,"center":[0,0,2],"operation":"new","body_name":"Inner"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + bind_recipe(&mut h, "Inner", "starter.glass.amber-tint", materials::Boundary::Box); + for binding in &mut h.app.render_workspace.view.materials.bindings { + binding.glass.ior = 1.0; // explicit index-matched experiment, not renderer conversion + binding.glass.recipe = None; + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["nested_media"], false); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("nested, touching or overlapping"), "{error}"); + } + h.app.render_workspace.view.cpu.nested_media = true; + // Geometry gives 2 mm outer + 2 mm inner, replacing rather than adding + // parent extinction inside the child. Linear RGB: + // sqrt(.98)*.84^(2/3), sqrt(.99)*.38^(2/3), .08^(2/3). + // Independent Reinhard+sRGB quantisation -> [182,158,110]. + check_start_pixel(&mut h, [182, 158, 110, 255]); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_cpu_optics_refuses_face_alpha_and_general_closed_geometry_without_repairs() { + let mut h = fixture(); + if !native_host(&mut h, "face_alpha_and_sphere") { + return; + } + h.app.run("appearance.assign", json!({"body":"Optics","faces":[[0,0,4]],"color":"#abcdef","opacity":0.5})).unwrap(); + let mut binding = h.app.render_workspace.view.materials.bindings[0].clone(); + materials::revalidate(&mut h.app, &mut binding).unwrap(); + h.app.render_workspace.view.materials.bindings[0] = binding; + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + assert_eq!(scene.meshes[0].opacity, 1.0); + assert!(scene.meshes[0].faces.iter().any(|face| face.opacity == 0.5)); + let document = h.app.session.doc.clone(); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + let error = h.app.run(command, request.clone()).unwrap_err(); + assert!(error.contains("opaque body and face"), "{error}"); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + h.app.run("solid.sphere", json!({"radius":3,"center":[30,0,3],"body_name":"Sphere","operation":"new"})).unwrap(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Sphere", "starter.glass.low-iron-clear", materials::Boundary::Box); + let request = image_params(&h.app).unwrap(); + for command in ["render.preflight", "render.start"] { + assert!(h.app.run(command, request.clone()).is_err(), "an explicitly selected Box still needs an actual box certificate"); + } + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Box); + } + + #[test] + fn cpu_optics_preserves_reflection_intent_for_existing_transport_conflict() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + cpu::set_reflection(&mut h.app, "Optics", Some(ReflectionMode::Mirror)).unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Optics"); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + // Retaining both preserves the engine's explicit same-target transport + // refusal; the adapter does not silently delete the reflection binding. + assert!(h.app.render_workspace.view.raytrace.reflections.is_some()); + } + + #[test] + fn cpu_optics_keeps_reflections_on_a_separate_exact_body() { + use solidcraft_engine::render::job::ReflectionMode; + let mut h = fixture(); + h.app.run("solid.box", json!({"length":2,"width":2,"height":2,"corner":[30,0,0],"body_name":"Reflector","operation":"new"})).unwrap(); + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + cpu::set_reflection(&mut h.app, "Reflector", Some(ReflectionMode::RoughSpecular)).unwrap(); + let before = h.app.render_workspace.view.raytrace.reflections.clone().unwrap(); + let request = wire(&h); + assert_eq!(request["raytrace"]["reflections"], json!(before)); + assert_eq!(request["raytrace"]["dielectrics"][0]["body_name"], "Optics"); + assert_eq!(request["raytrace"]["reflections"]["bodies"][0]["body"], "Reflector"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_original_library_ior_and_hdr_survive_check_start_and_captured_file_change() { + use sha2::{Digest, Sha256}; + use solidcraft_engine::render::job::{JobId, Phase}; + let mut h = fixture(); + if !native_host(&mut h, "library_ior_hdr") { + return; + } + let path = h.dir.join("original-optical-white.hdr"); + let bytes = original_hdr_bytes(128, true); + std::fs::write(&path, &bytes).unwrap(); + h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; + h.app.render_workspace.view.cpu.hdr = captured_hdr_input(path.to_str().unwrap()); + h.app.render_workspace.view.cpu.samples = 4; + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"][0]["ior"], 1.5, "the original recipe's IOR reaches the real consumer"); + let checked = h.app.run("render.preflight", request.clone()).unwrap(); + assert_eq!(checked["request"]["raytrace"], request["raytrace"]); + assert_eq!(image_params(&h.app).unwrap(), request); + let started = h.app.run("render.start", request.clone()).unwrap(); + let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); + // Start has captured immutable bytes; this does not depend on whether + // its tiny job has already finished by the time the file is replaced. + std::fs::write(&path, b"changed after capture").unwrap(); + let handle = h.app.session.render_job_handle(id).unwrap(); + let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + // CPU status carries exactly 32 byte values; the captured request uses + // the canonical lowercase hex HdrId wire form. Normalize independently + // of HdrId's production serializer/parser and keep absent/type failures. + let captured_sha256: [u8; 32] = serde_json::from_value(json!(status.environment).get("source_sha256").unwrap().clone()).unwrap(); + let expected_hex = request["environment"]["expected_sha256"].as_str().unwrap(); + assert_eq!(expected_hex.len(), 64); + assert!(expected_hex.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))); + let expected_sha256: [u8; 32] = std::array::from_fn(|index| u8::from_str_radix(&expected_hex[index * 2..index * 2 + 2], 16).unwrap()); + let original_sha256: [u8; 32] = Sha256::digest(&bytes).into(); + assert_eq!(captured_sha256, expected_sha256); + assert_eq!(captured_sha256, original_sha256); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + assert!(pixels.get_pixel(0, 0).0[..3].iter().all(|channel| *channel > 0), "real optical output must not be black"); + assert!(h.app.run("render.preflight", request).is_err(), "a fresh capture must detect the changed HDR"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_eight_optical_library_targets_admit_without_raising_the_ninth_target_limit() { + let mut h = fixture(); + if !native_host(&mut h, "eight_library_targets") { + return; + } + for index in 1..=8 { + h.app + .run( + "solid.box", + json!({"length":2,"width":2,"height":2,"corner":[30*index,0,0],"body_name":format!("Optics{index}"),"operation":"new"}), + ) + .unwrap(); + } + h.app.render_workspace.view.materials.bindings.clear(); + bind_recipe(&mut h, "Optics", "starter.glass.low-iron-clear", materials::Boundary::Box); + for index in 1..8 { + bind_recipe(&mut h, &format!("Optics{index}"), "starter.glass.low-iron-clear", materials::Boundary::Box); + } + let request = image_params(&h.app).unwrap(); + assert_eq!(request["raytrace"]["dielectrics"].as_array().unwrap().len(), 8); + h.app.run("render.preflight", request).unwrap(); + bind_recipe(&mut h, "Optics8", "starter.glass.low-iron-clear", materials::Boundary::Box); + assert!(image_params(&h.app).unwrap_err().contains(h.app.tr("render.cpu_optics_limit"))); + } + + #[test] + fn all_original_glass_recipes_keep_their_authored_coefficients_on_the_explicit_cpu_route() { + use solidcraft_engine::doc::appearance_pack::{Recipe, STARTER_PACK}; + let mut h = fixture(); + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let glass = materials::Glass::recipe(preset.id).unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.glass = glass; + if binding.glass.boundary == materials::Boundary::Closed { + binding.glass.boundary = materials::Boundary::Box; // explicit subset selection + } else { + assert!(binding.glass.shadows); + binding.glass.shadows = false; // explicit unsupported-policy edit + } + let request = wire(&h); + let material = &request["raytrace"]["dielectrics"][0]; + assert_eq!(material["ior"], recipe.dielectric_ior); + let sigma: [f64; 3] = serde_json::from_value(material["absorption_per_mm"].clone()).unwrap(); + for (sigma, transmission) in sigma.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + count += 1; + } + assert_eq!(count, 6); + assert!(materials::Glass::recipe("SELENE-AP-029").is_err(), "an opaque vial surrogate does not become physical glass"); + } + + #[test] + fn cpu_optical_route_messages_are_present_in_all_nine_delivered_languages() { + for language in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + let locale = crate::i18n::Locale::for_language(language); + for key in [ + "render.cpu_optics_boundary", + "render.cpu_optics_conflict", + "render.cpu_optics_enable", + "render.cpu_optics_explicit", + "render.cpu_optics_fixed", + "render.cpu_optics_help", + "render.cpu_optics_limit", + "render.cpu_optics_request", + "render.cpu_optics_saved", + "render.cpu_optics_unsupported", + ] { + assert_ne!(locale.text(key), key, "{language}: {key}"); + assert!(!locale.text(key).is_empty(), "{language}: {key}"); + } + } + } + + fn editor_frame(h: &mut Harness, events: Vec) { + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 2400.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("Optics")); + }, + ); + output.textures_delta.clear(); + } + + fn editor_click(h: &mut Harness, id: &str) { + let at = crate::scenario::rect_of(id).unwrap().center(); + for pressed in [true, false] { + editor_frame( + h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + editor_frame(h, vec![]); + } + + #[test] + fn clicked_cpu_optics_uses_existing_selection_editor_without_reinterpreting_gpu_binding() { + let mut h = fixture(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = false; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + assert!(runtime_image_request(&h.app, false).is_err(), "opening the editor grants no CPU intent"); + editor_click(&mut h, "render:glass-recipe-select"); + editor_click(&mut h, "render:glass:starter.glass.low-iron-clear"); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert!(runtime_image_request(&h.app, false).is_err(), "Closed recipe cannot turn itself into a Box"); + editor_click(&mut h, "render:optics-boundary-box"); + assert_eq!(wire(&h)["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + editor_click(&mut h, "render:cpu-optics-nested"); + assert_eq!(wire(&h)["nested_media"], true); + editor_click(&mut h, "render:cpu-optics-enable"); + assert!(runtime_image_request(&h.app, false).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn clicked_cpu_boundary_does_not_silently_clear_transmitted_shadow_or_subsurface_intent() { + let mut h = fixture(); + let glass = &mut h.app.render_workspace.view.materials.bindings[0].glass; + glass.shadows = true; + glass.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }); + editor_frame(&mut h, vec![]); + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + editor_click(&mut h, &heading); + editor_click(&mut h, "render:optics-boundary-thin"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows); + assert!(glass.subsurface.is_some(), "selecting a different CPU boundary is not consent to remove scattering"); + assert!(runtime_image_request(&h.app, false).is_err()); + editor_click(&mut h, "render:optics-boundary-box"); + let glass = &h.app.render_workspace.view.materials.bindings[0].glass; + assert!(glass.shadows, "the GPU boundary default must not erase unsupported CPU shadow intent"); + assert!(glass.subsurface.is_some()); + assert!(runtime_image_request(&h.app, false).is_err()); + } +} + +// Additive scope imports for the sealed optical fixtures; UI247 stays byte-identical. +use serde_json::Value; +use solidcraft_engine::render::StandardView; + +#[cfg(not(target_arch = "wasm32"))] +mod manual_final_cpu_feedback_tests { + use super::*; + use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, HostKind, JobHandle, PartialPreviewPlan, PartialPreviewProjection, Phase}; + + fn fixture(width: u32, height: u32, samples: u32, background: [u8; 3], case: &str) -> Option { + let mut h = Harness::new(); + let host = CpuHost::for_platform().unwrap(); + let available = host.kind() == HostKind::NativeWorker && host.is_available() && host.validate_integrator(Integrator::Raytrace).is_ok(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = width; + view.draft.height = height; + view.draft.background = background; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.draft.exposure_ev = 0.0; + view.transparent = false; + view.raytrace = RaytraceOptions { + primary_samples: 1, + lights: Some(Vec::new()), + shadows: false, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 83 }), + ..Default::default() + }; + h.ctx.input_mut(|input| input.max_texture_side = 8192); + if !available { + let wire = json!({"integrator":"raytrace","progressive_feedback":true, + "settings":{"width":width,"height":height,"background":background}, + "raytrace":{"primary_samples":1,"lights":[],"shadows":false, + "progressive":{"samples_per_pixel":samples,"seed":83}}}); + assert!(image_params(&h.app).is_err()); + assert!(h.app.run("render.preflight", wire.clone()).is_err()); + assert!(h.app.run("render.start", wire).is_err()); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.final_partial.is_none()); + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=false unsupported_refusal_asserted=true"); + return None; + } + eprintln!("MANUAL_FINAL_CPU_BRANCH case={case} cpu_supported=true"); + Some(h) + } + + fn actual_final(h: &mut Harness) -> JobHandle { + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.resolved.executor.as_str(), "cpu-raytrace"); + assert!(handle.frame().unwrap().is_some()); + assert!(handle.protected_preview_report().unwrap().is_some()); + handle + } + + // POLICY INPUTS ONLY, not a host-published PartialArc or a while-running receipt. + // Derive bounded display pixels from an actual completed native final, then + // author an explicit source-frontier descriptor to exercise the UI policy. + // No JobHandle, host status, PreviewInfo or GPU executor is fabricated. + fn install_policy_partial(h: &mut Harness, handle: &JobHandle, passes: u32, prefix: u64, sequence: u64) -> interactive::PartialSampling { + use sha2::{Digest, Sha256}; + let status = handle.status().unwrap(); + assert_eq!(status.progress.phase, Phase::Completed); + let frame = handle.frame().unwrap().unwrap(); + let source = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + let plan = PartialPreviewPlan::new(status.request.width, status.request.height).unwrap(); + let mut pixels = Vec::new(); + for index in 0..usize::try_from(plan.pixels()).unwrap() { + let source_index = plan.source_index(index).unwrap(); + let count = passes + u32::from((source_index as u64) < prefix); + if count == 0 { + pixels.extend_from_slice(&[0, 0, 0, 0]); + } else { + let x = source_index % status.request.width as usize; + let y = source_index / status.request.width as usize; + pixels.extend_from_slice(&source.get_pixel(x as u32, y as u32).0); + } + } + let png = super::partial_png_contract_encode(plan.width(), plan.height(), pixels); + let mut frame_info = frame.info.clone(); + frame_info.width = plan.width(); + frame_info.height = plan.height(); + frame_info.png_bytes = png.len() as u64; + frame_info.png_sha256 = format!("{:x}", Sha256::digest(&png)); + let info = PartialPreviewInfo { + frame: frame_info, + sequence, + source_width: status.request.width, + source_height: status.request.height, + completed_passes: passes, + updated_prefix: prefix, + projection: PartialPreviewProjection::TopLeftRepresentativeV1, + }; + let covered = vec![0; usize::try_from(plan.pixels()).unwrap()]; // committed misses have zero hit coverage + let expected = interactive::PartialExpectation { + job: handle.id(), + scene_generation: status.scene_generation, + request: &status.request, + final_dimensions: [status.request.width, status.request.height], + }; + let sampling = interactive::validate_partial_metadata(&expected, &info, png.len(), covered.len(), None).unwrap().unwrap(); + let image = + interactive::decode_partial_image(&status.request, &info, &png, &covered, sampling, h.ctx.input(|input| input.max_texture_side)).unwrap(); + let texture = h.ctx.load_texture("manual_final_policy_partial", image, egui::TextureOptions::NEAREST); + h.app.render_workspace.final_partial = Some(FinalPartialImage { info, sampling, image: Ok(texture) }); + sampling + } + + #[test] + fn native_manual_final_gui_opt_in_preserves_request_and_promotes_only_real_final() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "gui_opt_in") else { return }; + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let stored = setups::snapshot(&h.app).unwrap(); + assert!(serde_json::to_value(&stored).unwrap().get("progressive_feedback").is_none()); + let offline = image_request(&h.app).unwrap(); + assert!(offline.get("progressive_feedback").is_none()); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + h.app.render_workspace.view.raytrace.progressive = None; + assert!(image_params(&h.app).unwrap().get("progressive_feedback").is_none()); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 9, seed: 83 }); + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.cpu.checked.as_ref().unwrap().request, request); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!((status.request.width, status.request.height), (13, 7)); + let progressive = status.request.raytrace.as_ref().unwrap().progressive.unwrap(); + assert_eq!((progressive.samples_per_pixel, progressive.seed), (9, 83)); + let image = image::load_from_memory(handle.frame().unwrap().unwrap().png()).unwrap().to_rgba8(); + assert!(image.pixels().all(|pixel| pixel.0 == [17, 89, 203, 255])); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert!(display.preview.is_none() && display.partial.is_none()); + assert_eq!(display.logical_size, [13, 7]); + assert_eq!(display.info.job, handle.id()); + assert_eq!(setups::snapshot(&h.app).unwrap(), stored); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + } + + #[test] + fn native_final_partial_policy_keeps_global_unknown_full_framing_and_real_final_priority() { + let Some(mut h) = fixture(1025, 1, 3, [17, 89, 203], "partial_policy") else { return }; + let handle = actual_final(&mut h); + assert!(h.app.render_workspace.view.completed.is_none()); + // The top-left 1024 representatives are known, but source pixel1024 is not. + let sampling = install_policy_partial(&mut h, &handle, 0, 1024, 1); + assert!(sampling.source_unknown()); + assert_eq!(sampling.sample_range(), (0, 1)); + assert_eq!(sampling.sampled_source_pixels(), 1024); + let display = displayed_image(&h.app).unwrap(); + assert!(display.provisional() && display.partial.is_some() && display.preview.is_none()); + assert_eq!(display.logical_size, [1025, 1]); + assert_eq!((display.info.width, display.info.height), (1024, 1)); + assert_eq!(display.image.as_ref().unwrap().size(), [1024, 1]); + assert!(reduced_display(&h.app)); + let camera = Camera { distance: 37.0, ..Default::default() }; + h.app.render_workspace.view.result_camera = camera; + h.app.render_workspace.view.result_scale = ResultScale::Free; + h.app.render_workspace.view.result_job = Some(handle.id()); + let report = handle.protected_preview_report().unwrap(); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(handle.id())); + assert!(h.app.render_workspace.final_partial.is_none()); + let display = displayed_image(&h.app).unwrap(); + assert!(!display.provisional()); + assert_eq!(display.logical_size, [1025, 1]); + assert!(!reduced_display(&h.app)); + assert_eq!(h.app.render_workspace.view.result_camera, camera); + assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Free); + invalidate_images(&mut h.app); + assert!(h.app.render_workspace.final_partial.is_none()); + assert_eq!(handle.protected_preview_report().unwrap(), report, "presentation invalidation cannot reset the actual ledger"); + } + + #[test] + fn native_late_complete_policy_preserves_retained_export_then_reconciles_actual_frame() { + let Some(mut h) = fixture(13, 7, 9, [17, 89, 203], "late_complete") else { return }; + let first = actual_final(&mut h); + let ctx = h.ctx.clone(); + cache_render_images(&mut h.app, &ctx); + let first_bytes = first.frame().unwrap().unwrap().png().to_vec(); + h.app.render_workspace.view.draft.background = [91, 33, 187]; + let second = actual_final(&mut h); + assert_eq!(h.app.render_workspace.view.completed, Some(first.id())); + install_policy_partial(&mut h, &second, 0, 5, 1); + assert!(displayed_image(&h.app).unwrap().provisional()); + let old_path = h.dir.join("manual-final-retained.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":old_path})).unwrap(); + assert_eq!(std::fs::read(&old_path).unwrap(), first_bytes); + // Regression oracle for the observed event order: + // frame read absent -> later real status Completed -> real frame promoted + // BEFORE provisional clear/fallback. This calls the production policy on + // an actual completed native handle; it does not fake the earlier read. + assert!(!final_job_still_running(&mut h.app, &second)); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + cache_render_images(&mut h.app, &ctx); + assert!(!displayed_image(&h.app).unwrap().provisional()); + assert!(h.app.render_workspace.final_partial.is_none()); + let new_path = h.dir.join("manual-final-current.png"); + let export_job = h.app.render_workspace.view.completed.unwrap(); + h.app.run("render.export", json!({"job":export_job,"path":new_path})).unwrap(); + assert_eq!(std::fs::read(&new_path).unwrap(), second.frame().unwrap().unwrap().png()); + let final_pixels = image::load_from_memory(&std::fs::read(&new_path).unwrap()).unwrap().to_rgba8(); + assert!(final_pixels.pixels().all(|pixel| pixel.0 == [91, 33, 187, 255])); + assert!(!final_job_still_running(&mut h.app, &first), "a different selected final cannot be reconciled through an old handle"); + assert_eq!(h.app.render_workspace.view.completed, Some(second.id())); + } + fn author_box_optics(h: &mut Harness) { + h.app.run("solid.box", json!({"length":200,"width":200,"height":4,"center":[0,0,2],"body_name":"ManualOptics"})).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.ui.tab = "RENDER".into(); + let view = &mut h.app.render_workspace.view; + view.method = ImageMethod::CpuRaytrace; + view.draft.width = 1; + view.draft.height = 1; + view.draft.background = [255; 3]; + view.draft.stage = Default::default(); + view.draft.surfaces = Default::default(); + assert!(view.draft.stage.is_empty()); + assert!(view.draft.surfaces.is_empty()); + view.transparent = false; + view.draft.exposure_ev = 0.0; + view.raytrace.primary_samples = 1; + view.raytrace.lights = Some(Vec::new()); + view.raytrace.shadows = false; + view.cpu.environment = cpu::Environment::Constant; + view.cpu.color = [1.0; 3]; + view.cpu.intensity = 1.0; + h.app.cam = Camera { distance: 10.0, fov: 0.0, ..Default::default() }; + h.app.cam.set_view(StandardView::Top); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0); + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "ManualOptics").unwrap(); + let mut binding = materials::Binding::new(target, &h.app); + binding.glass_enabled = true; + binding.cpu_optics = true; + binding.glass = materials::Glass::recipe("starter.glass.low-iron-clear").unwrap(); + binding.glass.boundary = materials::Boundary::Box; // explicit author choice, not inferred geometry + h.app.render_workspace.view.materials.enabled = true; + h.app.render_workspace.view.materials.bindings.push(binding); + h.app.session.mark_saved(); + } + + fn editor_text(h: &mut Harness, events: Vec) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(shape) => { + text.push_str(shape.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, text); + } + } + _ => {} + } + } + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(480.0, 3200.0))), + events, + ..Default::default() + }, + |ui| { + ui.set_width(420.0); + materials::selection_controls(&mut h.app, ui, Some("ManualOptics")); + }, + ); + let mut text = String::new(); + for clipped in &output.shapes { + collect(&clipped.shape, &mut text); + } + output.textures_delta.clear(); + text + } + + #[test] + fn certification_note_draws_cpu_check_guidance_in_both_sampling_modes_and_legacy_gpu_note() { + let pending: Value = + serde_json::from_str(include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/pending/cpu-optical-certification.json"))) + .unwrap(); + let key = "render.cpu_optics_certification"; + for locale in ["ar", "de", "en", "es", "he", "ja", "ko", "vi", "zh"] { + assert_eq!(pending[locale].as_object().unwrap().len(), 1); + assert!(!pending[locale][key].as_str().unwrap().trim().is_empty()); + } + let mut h = Harness::new(); + h.ctx.global_style_mut(|style| style.animation_time = 0.0); + author_box_optics(&mut h); + h.app.render_workspace.view.raytrace.progressive = None; + let cpu_note = h.app.tr(key).to_string(); + let gpu_note = h.app.tr("render.material_certification").to_string(); + assert_ne!(cpu_note, key, "a missing catalog fallback is not a translated note"); + assert_ne!(gpu_note, "render.material_certification"); + let document = h.app.session.doc.clone(); + let before = ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed, + ); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let initial = editor_text(&mut h, Vec::new()); + if !initial.contains(&cpu_note) { + let heading = format!("dialog:section:{}", h.app.tr("render.appearance_editor.glass")); + let at = crate::scenario::rect_of(&heading).unwrap().center(); + for pressed in [true, false] { + editor_text( + &mut h, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + ); + } + } + for progressive in [None, Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 })] { + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.raytrace.progressive = progressive; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&cpu_note), "{text}"); + assert!(!text.contains(&gpu_note), "{text}"); + } + h.app.render_workspace.view.method = ImageMethod::GpuRaytrace; + let text = editor_text(&mut h, Vec::new()); + assert!(text.contains(&gpu_note), "{text}"); + assert!(!text.contains(&cpu_note), "{text}"); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + before, + ( + h.app.session.revision, + h.app.session.undo.len(), + h.app.session.is_dirty(), + h.app.render_workspace.view.job, + h.app.render_workspace.view.completed + ) + ); + // Text/layout evidence only: selecting a note never certifies a CPU/GPU render. + } + + #[test] + fn native_progressive_optical_recipe_keeps_authored_ior_certificate_and_final_capture() { + let Some(mut h) = fixture(1, 1, 5, [255; 3], "progressive_optics") else { return }; + author_box_optics(&mut h); + // This optical capture fixture requires normal incidence. StandardView::Top + // intentionally stops short of the pole; author an exact canonical view + // locally, preserving the shared helper's real near-pole GUI path. + h.app.cam = Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, roll: 0.0, up: solidcraft_engine::render::UpAxis::Z, ..h.app.cam }; + assert!(h.app.cam.is_valid()); + assert_eq!(h.app.cam.fov, 0.0); + assert_eq!(h.app.cam.distance, 10.0); + assert_eq!(h.app.cam.target, solidcraft_engine::geom::Vec3::new(0.0, 0.0, 2.0)); + assert_eq!( + (h.app.cam.yaw, h.app.cam.pitch, h.app.cam.roll, h.app.cam.up), + (0.0, std::f64::consts::FRAC_PI_2, 0.0, solidcraft_engine::render::UpAxis::Z) + ); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 13 }); + // The orthographic pixel's entire jitter support lies in +/-4mm, + // strictly inside the independently authored +/-100mm box footprint. + assert_eq!(h.app.cam.half_height(), 4.0); + for (x, y) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { + let (origin, direction) = h.app.cam.ray(x, y, 1.0, 1.0); + assert!(direction.x.abs() < 1e-12 && direction.y.abs() < 1e-12); + assert!((direction.z.abs() - 1.0).abs() < 1e-12); + let point = origin + direction * ((4.0 - origin.z) / direction.z); + assert!(point.x.abs() <= 4.0 + 1e-9 && point.y.abs() <= 4.0 + 1e-9); + assert!(point.x.abs() < 100.0 && point.y.abs() < 100.0); + } + let document = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let binding_before = format!("{:?}", h.app.render_workspace.view.materials.bindings[0]); + let request = image_params(&h.app).unwrap(); + assert_eq!(request["progressive_feedback"], true); + let optics = &request["raytrace"]["dielectrics"][0]; + assert_eq!(optics["body_name"], "ManualOptics"); + assert_eq!(optics["boundary"], "closed_box"); + assert_eq!(optics["ior"], 1.5, "the production recipe IOR is not reduced for this case"); + for (index, transmission) in [0.98_f64, 0.99, 1.0].into_iter().enumerate() { + let expected = -transmission.ln() / 4.0; + assert!((optics["absorption_per_mm"][index].as_f64().unwrap() - expected).abs() < 1e-15); + } + let checked = h.app.session.execute("render.preflight", &request).unwrap(); + let handle = actual_final(&mut h); + let status = handle.status().unwrap(); + assert_eq!(serde_json::to_value(&status.request).unwrap(), checked["request"]); + assert_eq!(json!(status.request.raytrace), request["raytrace"]); + assert!(!status.options.nested_media); + let frame = handle.frame().unwrap().unwrap(); + let pixels = image::load_from_memory(frame.png()).unwrap().to_rgba8(); + assert_eq!(pixels.dimensions(), (1, 1)); + let pixel = pixels.get_pixel(0, 0).0; + assert_eq!(pixel[3], 255); + assert!(pixel[..3].iter().any(|value| *value > 0)); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials.bindings[0]), binding_before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + // Actual CPU capture/completion + nonblack optical smoke, not a full + // Fresnel/TIR oracle or a partial-optical-tree while-running receipt. + } +} + +// These exercise GUI navigation against the real cooperative Raster host. +// They do not qualify CPU raytracing, progressive cadence or GPU rendering. +fn auto_result_raster_fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":3,"width":4,"height":5})).unwrap(); + enter(&mut h.app, true).unwrap(); + let host = solidcraft_engine::render::job::CpuHost::cooperative(); + h.app.session.set_render_job_host(Some(host.clone())).unwrap(); + h.app.render_workspace.image_host = Some(host); + h.app.render_workspace.view.method = ImageMethod::Raster; + h.app.render_workspace.view.draft.width = 13; + h.app.render_workspace.view.draft.height = 7; + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h +} + +#[test] +fn auto_result_success_opens_once_and_explicit_model_survives_real_completion() { + use solidcraft_engine::render::job::Phase; + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + assert!(!h.app.render_workspace.view.result); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let camera = h.app.cam; + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(h.app.render_workspace.view.result); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(ribbon::action_ready(&h.app, "render.export").is_err()); + let request = handle.status().unwrap().request; + assert_eq!((request.width, request.height, request.integrator), (13, 7, Integrator::Raster)); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.result); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + assert!(!h.app.render_workspace.view.result); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result, "publication/repaint must respect an explicit Model selection"); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded cooperative Raster work must complete"); + assert_eq!((frame.info.width, frame.info.height), (13, 7)); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(ribbon::action_ready(&h.app, "render.export").is_ok()); + for _ in 0..3 { + cache_render_images(&mut h.app, &h.ctx); + assert!(!h.app.render_workspace.view.result); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn auto_result_disabled_keeps_both_selected_views_through_start_and_completion() { + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + crate::prefs::set(&mut h.app, &json!({"render_open_result_on_start":false})).unwrap(); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert!(handle.frame().unwrap().is_none()); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + if handle.frame().unwrap().is_some() { + break; + } + } + assert!(handle.frame().unwrap().is_some(), "bounded cooperative Raster work must complete"); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + } +} + +#[test] +fn auto_result_check_invalid_start_and_real_queue_full_preserve_selected_view() { + use solidcraft_engine::render::job::Phase; + for selected in [false, true] { + let mut h = auto_result_raster_fixture(); + assert!(h.app.preferences.render_open_result_on_start); + h.app.run("render.result.view", json!({"view":if selected {"image"} else {"model"}})).unwrap(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + ribbon::perform_job(&mut h.app, "render.preflight").unwrap(); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + h.app.render_workspace.view.draft.width = 0; + assert!(ribbon::perform_job(&mut h.app, "render.preflight").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(ribbon::perform_job(&mut h.app, "render.start").is_err()); + assert_eq!(h.app.render_workspace.view.result, selected); + h.app.render_workspace.view.draft.width = 13; + let request = image_params(&h.app).unwrap(); + let mut jobs = Vec::new(); + // Queue two real jobs without registering a GUI job. + // No pump or worker thread runs between admission and the third Start. + for _ in 0..2 { + let reply = h.app.session.execute("render.start", &request).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + jobs.push(handle); + } + ribbon::action_ready(&h.app, "render.start").unwrap(); + let error = ribbon::perform_job(&mut h.app, "render.start").unwrap_err(); + assert!(error.contains("this document already has an active and pending render"), "expected real document QueueFull: {error}"); + assert_eq!(h.app.render_workspace.view.result, selected); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.result, selected); + for handle in jobs { + assert_eq!(handle.status().unwrap().progress.phase, Phase::Queued); + assert!(handle.frame().unwrap().is_none()); + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + } +} + +#[test] +fn product_preview_exposure_is_bounded_without_rewriting_method_or_advanced_intent() { + let mut h = Harness::new(); + h.app.render_workspace.view.samples = 512; + h.app.render_workspace.view.max_depth = 8; + h.app.render_workspace.view.seed = 42; + h.app.render_workspace.view.raytrace.primary_samples = 4; + h.app.render_workspace.view.raytrace.shadows = false; + let cpu = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + let gpu = (h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len()); + let camera = h.app.cam; + for ev in [-32.0, -3.5, -0.0, 0.0, 1.75, 32.0] { + h.app.render_workspace.view.draft.exposure_ev = ev; + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, ev, "method selection cannot silently reset saved exposure intent"); + let preview = product_preview_exposure(&h.app).unwrap(); + // Model uses the common EV for every final method, even with Interactive Off. + // This intentionally supersedes this unpublished test's Raster-only helper contract. + assert_eq!(preview.ev(), ev as f32); + assert_eq!(interactive::inspect(&h.app)["phase"], "Off"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), cpu); + assert_eq!((h.app.render_workspace.view.samples, h.app.render_workspace.view.max_depth, h.app.render_workspace.view.seed), gpu); + } + } + for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace, ImageMethod::Raster] { + select_image_method(&mut h.app, method); + for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -32.001, 32.001] { + h.app.render_workspace.view.draft.exposure_ev = invalid; + let error = product_preview_exposure(&h.app).unwrap_err(); + assert_eq!(error, h.app.tr("render.product_exposure_invalid")); + assert_eq!(h.app.render_workspace.view.method, method); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev.to_bits(), invalid.to_bits(), "a refusal must not clamp or replace intent"); + // The real Model show route must report the typed exposure refusal before + // its no-GPU fallback, without starting a final or Interactive capture. + let mut output = h.ctx.run_ui(Default::default(), |ui| show(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&output).any(|shape| shape.galley.text() == error)); + output.textures_delta.clear(); + assert!(h.app.render_workspace.view.job.is_none()); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(!h.app.render_workspace.interactive.pending()); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!((h.app.session.revision, h.app.session.undo.len()), history); + assert_eq!(h.app.cam, camera); +} + +#[test] +fn raster_shot_exposure_uses_the_existing_slider_and_one_undoable_saved_command() { + let mut h = frame_editor_fixture(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + h.app.run("solid.box", json!({"length":10,"width":20,"height":5,"body_name":"Exposure subject"})).unwrap(); + h.app.run("view.render_select", json!({"kind":"shot","id":"Hero"})).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + select_image_method(&mut h.app, ImageMethod::Raster); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.75, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 0.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), saved.exposure_ev as f32); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + #[cfg(not(target_arch = "wasm32"))] + { + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + let (_, geometry) = gpu_scene(&scene).unwrap(); + let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); + let eye = camera.eye().to_f32(); + let capture = |exposure| { + crate::gpu::render_product_offscreen_exposure( + geometry.clone(), + None, + camera.view_proj(1.0, radius).to_f32(), + camera.back().to_f32(), + [eye[0], eye[1], eye[2], if camera.fov > 0.0 { 1.0 } else { 0.0 }], + 64, + false, + exposure, + ) + }; + if let Some(zero) = capture(Default::default()) { + let exposed = capture(product_preview_exposure(&h.app).unwrap()).expect("the same supported capture route must complete"); + assert_ne!(exposed, zero, "saved GUI exposure must reach actual product-shader pixels"); + assert_eq!(&exposed[..4], &zero[..4], "the capture backplate is not exposed"); + assert_eq!(capture(Default::default()).unwrap(), zero, "returning to zero restores the exact captured response"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=true"); + } else { + assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "required GUI product capture is unavailable"); + eprintln!("RASTER_GUI_EXPOSURE_CAPTURE supported=false"); + } + } + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Original F1 regressions: real native accepted pixels, no injected cache/frame. +// This first alignment block covers accepted camera and framing, not a new +// proof of all possible scene/placement/visibility changes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_after_finished_pan_blocks_current_camera_targets_but_keeps_navigation_and_escape") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let handle = interactive::test_current(&h.app).unwrap().unwrap(); + let (accepted, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((accepted.job, samples, complete), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + let camera = h.app.cam; + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let end = at + egui::vec2(28.0, 12.0); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Middle, pressed: true, modifiers: egui::Modifiers::NONE }, + ], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![egui::Event::PointerMoved(end)]); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: end, button: egui::PointerButton::Middle, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_ne!(h.app.cam.target, camera.target, "the real shared middle-pan must have moved the camera"); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert!(!interactive::awaiting_current_frame(&h.app), "this is known paused evidence, not the existing blank/Unknown guard"); + assert!(interactive::blocks_geometry_input(&h.app)); + let viewport = h.app.viewport.rect.unwrap(); + let geometry_rect = interactive::geometry_input_rect(&h.app, viewport); + let projection = crate::viewport::projection(&h.app, geometry_rect); + let current_hit = projection.to_screen(camera.target).unwrap(); + assert!(geometry_rect.contains(current_hit)); + assert!( + crate::viewport::pick(&h.app, &projection, current_hit) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }), + "prove there really is a current-camera target for the new guard to reject" + ); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none() && h.app.session.selection.is_empty()); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, current_hit, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(!h.app.render_workspace.view.assign.painting && !h.app.render_workspace.view.assign.sampling); + let (retained, retained_samples, retained_complete, retained_texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (retained.job, retained.png_sha256, retained_samples, retained_complete, retained_texture), + (job, accepted.png_sha256, samples, complete, texture) + ); + let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.01, false, true); + assert!(painted, "the retained image stays visible as a reference"); + output.textures_delta.clear(); + assert!(!h.app.render_workspace.interactive.pending()); + interactive_assert_final_export_isolation(&mut h, &handle); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_aligned_known_image_supports_repeated_material_edits_and_uses_its_painted_rectangle") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let viewport = h.app.viewport.rect.unwrap(); + let pixels = interactive::geometry_input_rect(&h.app, viewport); + assert!(pixels.width() < viewport.width(), "the original square image is letterboxed in this landscape viewport"); + assert!((pixels.width() - pixels.height()).abs() <= f32::EPSILON * pixels.height().max(1.0)); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assert!(!interactive::blocks_geometry_input(&h.app), "Pause alone and an earlier appearance edit cannot block aligned input"); + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert_eq!(h.app.session.doc.appearances.bodies["Subject"].name, name); + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert_eq!(interactive::inspect(&h.app)["stale"], true); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!interactive::blocks_geometry_input(&h.app)); + } + assign::stop(&mut h.app); + let selection = h.app.session.selection.clone(); + let outside_pixels = egui::pos2(viewport.left() + 1.0, viewport.center().y); + assert!(!pixels.contains(outside_pixels)); + interactive_canvas_input_click(&mut h, &mut time, outside_pixels, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection, "letterbox margins are not pixel-aligned CAD targets"); + assert!(!h.app.render_workspace.interactive.pending()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate() { + let Some((mut h, mut time, at)) = + interactive_canvas_input_fixture("paused_known_image_rejects_authored_aspect_change_without_blanket_pause_or_final_gate") + else { + return; + }; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + let width = h.app.render_workspace.view.draft.width; + assert!(!interactive::blocks_geometry_input(&h.app)); + let document = h.app.session.doc.clone(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + assign::tile(&mut h.app, json!({"appearance":"ABS - Red"}), true).unwrap(); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_some(), "start a real drag against aligned accepted pixels"); + h.app.render_workspace.view.draft.width = width * 2; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app)); + assert!(!interactive::awaiting_current_frame(&h.app)); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + interactive_canvas_input_frame( + &mut h, + &mut time, + vec![egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }], + ); + assert!(assign::preview(&h.app).is_none() && assign::hover(&h.app).is_none()); + assert!(!assign::cancel(&mut h.app), "the blocked release must drain the real drag"); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!( + (h.app.session.revision, h.app.session.undo.len()), + (revision, undo), + "the guard must stop a framing-only drag without relying on the document revision guard" + ); + h.app.render_workspace.view.draft.width = width; + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the accepted aspect restores aligned same-camera input"); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app), "the manual Result path owns its own camera and input policy"); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(interactive::awaiting_current_frame(&h.app) && interactive::blocks_geometry_input(&h.app)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +// Geometry/placement/visibility successor: original native snapshots and CAD +// commands only. No injected publications, host factory or scheduling barrier. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_geometry_move_rejects_real_new_targets_and_preserves_old_pixels") + else { + return; + }; + let world = h.app.session.interactive_cached_world_state().unwrap(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + let retained = interactive::test_cache(&h.app).unwrap(); + assert_eq!((retained.0.job, retained.1, retained.2), (job, 16, true)); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("solid.move", json!({"bodies":["Subject"],"translate":[2,0,0]})).unwrap(); + let moved = h.app.session.interactive_cached_world_state().unwrap(); + assert!(!Arc::ptr_eq(&world, &moved)); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "must reject before observed is refreshed, using accepted capture authority"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let center = moved.body("Subject").unwrap().mesh().bounds().center(); + let at = projection.to_screen(center).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Subject") }) + ); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.viewport.hover.is_none()); + assert_eq!(h.app.session.selection, selection); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(h.app.viewport.context_menu.is_none()); + assign::arm(&mut h.app, json!({"appearance":"ABS - Red"})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + let after = interactive::test_cache(&h.app).unwrap(); + assert_eq!( + (after.0.job, after.0.png_sha256, after.1, after.2, after.3), + (retained.0.job, retained.0.png_sha256, retained.1, retained.2, retained.3) + ); + assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned() { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_world_visibility_restore_keeps_selection_and_repeated_material_edits_aligned") + else { + return; + }; + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"center":[22,0,2],"body_name":"Other"})).unwrap(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + let world = h.app.session.interactive_cached_world_state().unwrap(); + let camera = h.app.cam; + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":false})).unwrap(); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "unchanged world alone cannot certify a changed visible body set"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(world.body("Other").unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == "Other") }), + "a still-visible current-world target exists" + ); + let selection = h.app.session.selection.clone(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + h.app.run("browser.visibility", json!({"items":["Subject"],"visible":true})).unwrap(); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(!interactive::blocks_geometry_input(&h.app), "restoring the exact accepted visibility can restore alignment without recapture"); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert!(h.app.session.selection.contains(&solidcraft_engine::Sel::Body { name: "Other".into() })); + assert!(!interactive::blocks_geometry_input(&h.app), "selection is not a scene invalidation"); + let undo = h.app.session.undo.len(); + for (index, name) in ["ABS - Blue", "ABS - Red"].into_iter().enumerate() { + assign::arm(&mut h.app, json!({"appearance":name})).unwrap(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.doc.appearances.bodies["Other"].name, name); + assert_eq!(h.app.session.undo.len(), undo + index + 1); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + assert!(!interactive::blocks_geometry_input(&h.app), "render-only refresh must keep the accepted geometric identity usable"); + } + assert_eq!(h.app.cam, camera); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + assert!(!h.app.render_workspace.interactive.pending()); + assign::stop(&mut h.app); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world() { + for capture in [true, false] { + let Some((mut h, mut time, _)) = + interactive_canvas_input_fixture("paused_same_camera_occurrence_capture_and_pending_move_require_new_accepted_world") + else { + return; + }; + let component = h.app.run("component.create", json!({"name":"AlignmentPart","grounded":false})).unwrap(); + h.app.run("solid.box", json!({"length":6,"width":6,"height":4,"body_name":"Placed"})).unwrap(); + h.app.run("component.activate", json!({"component":0})).unwrap(); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[20,0,0]})).unwrap(); + let world = h.app.session.world_state(); // Explicit real test preparation, never performed by the guard. + let placed = world.bodies.iter().find(|body| body.name != "Subject").unwrap().name.clone(); + let scene = solidcraft_engine::product_scene::extract(&h.app.session).unwrap(); + h.app.cam.fit(&scene.bounds); + interactive_canvas_input_frame(&mut h, &mut time, vec![]); + assert!(Arc::ptr_eq(&world, &h.app.session.interactive_cached_world_state().unwrap())); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + let job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + time += 0.4; + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + let camera = h.app.cam; + assert!(!interactive::blocks_geometry_input(&h.app)); + h.app.run("occurrence.move", json!({"occurrence":component["occurrence"],"translate":[3,0,0],"capture":capture})).unwrap(); + assert_eq!(h.app.cam, camera); + assert!(interactive::blocks_geometry_input(&h.app), "a missing/stale prepared world is not accepted-scene authority"); + let moved = h.app.session.world_state(); // Warm through the ordinary API only in the original test. + assert!(!Arc::ptr_eq(&world, &moved)); + assert!(interactive::blocks_geometry_input(&h.app), "warming a new current world must not bless the old accepted pixels"); + let viewport = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, interactive::geometry_input_rect(&h.app, viewport)); + let at = projection.to_screen(moved.body(&placed).unwrap().mesh().bounds().center()).unwrap(); + assert!( + crate::viewport::pick(&h.app, &projection, at) + .iter() + .any(|hit| { matches!(hit, crate::viewport::Hit::Face { body, .. } if body == &placed) }) + ); + let selection = h.app.session.selection.clone(); + let document = h.app.session.doc.clone(); + let undo = h.app.session.undo.len(); + interactive_canvas_input_click(&mut h, &mut time, at, egui::PointerButton::Primary, egui::Modifiers::NONE); + assert_eq!(h.app.session.selection, selection); + assert!(h.app.viewport.hover.is_none()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(interactive::test_cache(&h.app).unwrap().0.job, job); + h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); + let new_job = interactive_recovery_require_success(&mut h, time + 0.3, time + 0.4); + assert_ne!(new_job, job); + assert!(!interactive::blocks_geometry_input(&h.app), "only the new accepted capture can establish the moved scene"); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + } +} + +// Common Model EV must stop at captured-image boundaries; these use real producers. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "product_preview_exposure_does_not_regrade_a_real_native_cpu_interactive_png") { + return; + } + assert!(h.app.viewport.gpu.is_none(), "real show has no product-GPU fallback in this fixture"); + h.app.render_workspace.view.draft.exposure_ev = 1.0; + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, false); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let status = held.job.status().unwrap(); + assert_eq!(status.request.raster_exposure_ev, 0.0, "CPU request must not gain a second Raster EV"); + assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, 1.0); + let frame = held.job.frame().unwrap().unwrap(); + let original = frame.png().to_vec(); + held.sender.send(held.reply).unwrap(); + let (mut accepted, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let texture = interactive::test_cache(&h.app).unwrap().3; + let uploaded = &accepted.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [16, 16]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + accepted.textures_delta.clear(); + + // Current capture first, then a paused image after a different common EV edit. + // Both must paint their captured texture, without entering the live Model branch. + for (step, ev) in [1.0, 2.0].into_iter().enumerate() { + if step == 1 { + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.draft.exposure_ev = ev; + } + assert_eq!(product_preview_exposure(&h.app).unwrap().ev(), ev as f32); + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(420.0, 420.0))), + time: Some(epoch + 0.4 + step as f64 * 0.1), + ..Default::default() + }, + |ui| show(&mut h.app, ui), + ); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.error_gpu_preview"))); + assert!(!output.textures_delta.set.contains_key(&texture), "captured PNG is not uploaded or graded again"); + output.textures_delta.clear(); + assert!( + h.ctx.tessellate(output.shapes, output.pixels_per_point).iter().any( + |shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == texture && !mesh.indices.is_empty()) + ) + ); + let (cached, samples, complete, id) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, cached.png_sha256, samples, complete, id), (held.job.id(), frame.info.png_sha256.clone(), 16, true, texture)); + assert_eq!(held.job.frame().unwrap().unwrap().png(), original.as_slice()); + assert!(!h.app.render_workspace.interactive.pending(), "show must not dispatch a replacement capture"); + interactive_assert_final_export_isolation(&mut h, &held.job); + } + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn product_preview_exposure_does_not_regrade_or_validate_a_retained_real_result() { + let mut h = auto_result_raster_fixture(); + ribbon::perform_job(&mut h.app, "render.start").unwrap(); + let job = h.app.render_workspace.view.job.unwrap(); + let handle = h.app.session.render_job_handle(job).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..128 { + host.pump(16_384).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + if handle.frame().unwrap().is_some() { + break; + } + } + let frame = handle.frame().unwrap().expect("bounded real cooperative Raster result"); + let original = frame.png().to_vec(); + h.app.run("render.result.view", json!({"view":"image"})).unwrap(); + let mut texture = None; + for ev in [1.0, -1.0, f64::NAN] { + h.app.render_workspace.view.draft.exposure_ev = ev; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }, + |ui| show(&mut h.app, ui), + ); + assert!(h.app.render_workspace.view.result); + let id = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + if let Some(prior) = texture { + assert_eq!(id, prior); + assert!(!output.textures_delta.set.contains_key(&id)); + } else { + let uploaded = &output.textures_delta.set.get(&id).unwrap().first().unwrap().image; + let egui::ImageData::Color(pixels) = uploaded; + let png = image::load_from_memory_with_format(&original, image::ImageFormat::Png).unwrap().to_rgba8(); + assert_eq!(pixels.size, [13, 7]); + assert_eq!(pixels.pixels.len(), png.pixels().len()); + assert!( + pixels + .pixels + .iter() + .zip(png.pixels()) + .all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + } + texture = Some(id); + assert!(!crate::test_support::text_shapes(&output).any(|s| s.galley.text() == h.app.tr("render.product_exposure_invalid"))); + output.textures_delta.clear(); + assert!( + h.ctx + .tessellate(output.shapes, output.pixels_per_point) + .iter() + .any(|shape| matches!(&shape.primitive, egui::epaint::Primitive::Mesh(mesh) if mesh.texture_id == id && !mesh.indices.is_empty())) + ); + assert_eq!(handle.frame().unwrap().unwrap().png(), original.as_slice()); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + } + let path = h.dir.join("common-model-ev-retained-result.png"); + h.app.run("render.export", json!({"job":job,"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), original); +} + +#[test] +fn editing_an_inactive_selected_shot_keeps_the_active_setup_draft_and_camera() { + let mut h = frame_editor_fixture(); + assert_eq!(shot::selected(&h.app), Some("Hero")); + assert_eq!(h.app.render_workspace.view.name, "Studio", "selection does not activate a saved setup"); + let active = serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(); + let camera = h.app.cam; + let before = h.app.session.doc.to_json(); + let studio = h.app.session.doc.render.setups.get("Studio").cloned(); + let mut expected_hero = h.app.session.doc.render.setups["Hero"].clone(); + expected_hero.exposure_ev = 1.5; + let undo = h.app.session.undo.len(); + shot::edit_settings(&mut h.app, "Hero", json!({"exposure_ev":1.5})).unwrap(); + assert_eq!(h.app.session.doc.render.setups["Hero"], expected_hero); + assert_eq!(h.app.session.doc.render.setups.get("Studio").cloned(), studio); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.undo.len(), undo + 1, "only the saved Hero edit enters history"); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.render_workspace.view.name, "Studio"); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.draft).unwrap(), active); + assert_eq!(h.app.cam, camera); +} + +// Integration of the common ±32 EV contract with the existing Shot editor. +// This exercises egui input and the saved command, without opening a GPU device. +#[test] +fn cpu_shot_exposure_reaches_extended_range_via_slider_and_one_saved_command() { + let mut h = frame_editor_fixture(); + h.app.run("render.settings.set", json!({"name":"Hero","set":{"job":{"method":"cpu_raytrace"},"exposure_ev":0.0}})).unwrap(); + h.app.render_workspace.view.name = "Hero".into(); + setups::load(&mut h.app); + assert_eq!(h.app.render_workspace.view.name, "Hero"); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + h.call("ui.resize", json!({"width":1600,"height":1800})); + h.frames(4); + let track = crate::scenario::rect_of("dialog:slider_track:Exposure").unwrap(); + assert!(track.width() > 20.0); + let before = h.app.session.doc.to_json(); + let camera = h.app.cam; + let size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); + let undo = h.app.session.undo.len(); + let start = track.center(); + let end = egui::pos2(track.left() + track.width() * 0.875, track.center().y); + h.step(&json!({"drag":[[start.x,start.y],[end.x,end.y]],"steps":8})).unwrap(); + let saved = &h.app.session.doc.render.setups["Hero"]; + assert!(saved.exposure_ev.is_finite() && saved.exposure_ev > 16.0 && saved.exposure_ev <= 32.0); + assert_eq!(h.app.render_workspace.view.draft.exposure_ev, saved.exposure_ev); + // The shared production constructor captures portable intent without host admission. + assert!(!setups::has_runtime_inputs(&h.app)); + assert_eq!(image_request(&h.app).unwrap()["settings"]["exposure_ev"], json!(saved.exposure_ev)); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(h.app.session.undo.len(), undo + 1); + assert_eq!(h.app.cam, camera); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), size); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); +} + +// Explicit catalogue staging, not a scalar appearance assignment or transport oracle. +mod glass_library_bridge { + use super::*; + use solidcraft_engine::{ + Sel, + doc::appearance_pack::{Recipe, STARTER_PACK}, + }; + + fn fixture() -> Harness { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":20,"width":20,"height":4,"body_name":"Optics"})).unwrap(); + enter(&mut h.app, true).unwrap(); + h.app.run("render.scene", json!({})).unwrap(); + h.app.run("select.set", json!({"items":[Sel::Body { name:"Optics".into() }]})).unwrap(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.stage = Stage::Look; + h.app.render_workspace.view.draft.width = 64; + h.app.render_workspace.view.draft.height = 64; + h.app.render_workspace.view.transparent = false; + h.app.render_workspace.view.raytrace.progressive = None; + h.app.session.mark_saved(); + h + } + + #[test] + fn library_bridge_stages_all_six_authored_recipes_without_cpu_permission_or_design_changes() { + let mut count = 0; + for preset in STARTER_PACK { + let Recipe::Glass(recipe) = preset.recipe else { continue }; + let mut h = fixture(); + let doc = h.app.session.doc.clone(); + let before = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + let options = serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(); + library::stage_glass(&mut h.app, preset.id).unwrap(); + let binding = &h.app.render_workspace.view.materials.bindings[0]; + assert_eq!(binding.target.name, "Optics"); + assert!(binding.target.stable_target.is_some()); + assert!(binding.glass_enabled && !binding.cpu_optics && !binding.maps_enabled && !binding.coat_enabled); + assert_eq!(binding.glass.recipe, Some(preset.id)); + assert_eq!(binding.glass.ior, recipe.dielectric_ior); + for (sigma, transmission) in binding.glass.absorption.into_iter().zip(recipe.transmission_linear_rgb) { + assert!(((-sigma * recipe.reference_path_mm).exp() - transmission).abs() < 1e-12); + } + match recipe.boundary { + solidcraft_engine::doc::appearance_pack::GlassBoundary::Closed => { + assert_eq!(binding.glass.boundary, materials::Boundary::Closed); + assert!(!binding.glass.shadows); + } + solidcraft_engine::doc::appearance_pack::GlassBoundary::Thin { thickness_mm } => { + assert_eq!(binding.glass.boundary, materials::Boundary::Thin); + assert_eq!(binding.glass.thickness, thickness_mm); + assert!(binding.glass.shadows, "preparing a Thin recipe is not consent to remove transmitted shadows"); + } + } + assert_eq!(h.app.render_workspace.view.method, ImageMethod::CpuRaytrace); + assert_eq!(serde_json::to_value(&h.app.render_workspace.view.raytrace).unwrap(), options); + assert!(runtime_image_request(&h.app, false).is_err(), "CPU permission is still explicit"); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(before, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); + assert!(matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if items == &h.app.session.selection)); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + count += 1; + } + assert_eq!(count, 6); + } + + #[test] + fn library_bridge_requires_stable_glass_id_and_keeps_scalar_assignment_guards() { + let mut h = fixture(); + let opaque = STARTER_PACK.iter().find(|p| matches!(p.recipe, Recipe::Opaque(_))).unwrap(); + for id in ["Glass - Clear", "Glass Recipe - Low Iron Clear", opaque.id, "starter.glass.not-a-recipe"] { + assert!(library::stage_glass(&mut h.app, id).is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + let catalog = h.app.run("appearance.library", json!({})).unwrap(); + let glass = catalog["appearances"].as_array().unwrap().iter().find(|p| p["id"] == "starter.glass.low-iron-clear").unwrap(); + assert_eq!(glass["available"], false); + for appearance in ["starter.glass.low-iron-clear", "Glass Recipe - Low Iron Clear"] { + assert!(h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":appearance,"color":"#ffffff","opacity":1.0})).is_err()); + } + h.app.run("appearance.assign", json!({"bodies":["Optics"],"appearance":"Glass - Clear"})).unwrap(); + assert!(h.app.session.doc.appearances.bodies["Optics"].opacity < 1.0); + assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "legacy alpha is never promoted to physical glass"); + } + + #[test] + fn library_bridge_refuses_face_component_empty_multiple_and_raster_targets() { + let mut h = fixture(); + h.app.run("select.filter", json!({"mode":"face"})).unwrap(); + let hit = crate::viewport::Hit::Face { body: "Optics".into(), index: 0, point: solidcraft_engine::geom::Vec3::ZERO }; + let face = crate::viewport::candidate(&h.app, &[hit]).unwrap().1; + assert!(matches!(face, Sel::Face { .. })); + let component = h.app.run("component.create", json!({"name":"Unassigned component"})).unwrap(); + let occurrence = component["occurrence"].as_u64().unwrap(); + for selection in [ + vec![], + vec![face], + vec![Sel::Occurrence { path: vec![occurrence] }], + vec![Sel::Body { name: "Optics".into() }, Sel::Body { name: "Optics".into() }], + ] { + h.app.session.selection = selection; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + } + h.app.session.selection = vec![Sel::Body { name: "Optics".into() }]; + h.app.render_workspace.view.method = ImageMethod::Raster; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.method, ImageMethod::Raster); + } + + #[test] + fn library_bridge_hidden_stale_document_and_changed_target_never_refresh_a_binding() { + let mut h = fixture(); + h.app.session.visibility.hidden_bodies.push("Optics".into()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert!(h.app.render_workspace.view.materials.bindings.is_empty()); + h.app.session.visibility.hidden_bodies.clear(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + let original = h.app.render_workspace.view.materials.bindings[0].clone(); + h.app.render_workspace.view.materials.bindings[0].target.ordinal += 1; + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].target.ordinal, original.target.ordinal + 1); + h.app.render_workspace.view.materials.bindings[0] = original.clone(); + h.app.session.doc = Arc::new((*h.app.session.doc).clone()); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + h.app.render_workspace.view.materials.bindings[0] = original; + h.app.run("appearance.assign", json!({"bodies":["Optics"],"color":"#123456"})).unwrap(); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err(), "CAD revision is not silently revalidated"); + } + + #[test] + fn library_bridge_conflicts_preserve_permission_shadows_scattering_and_other_material_intent() { + for conflict in 0..4 { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.thin-clear").unwrap(); + let binding = &mut h.app.render_workspace.view.materials.bindings[0]; + binding.cpu_optics = true; + match conflict { + 0 => binding.coat_enabled = true, + 1 => binding.maps_enabled = true, + 2 => { + binding.glass.subsurface = + Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.1, anisotropy: 0.0 }) + } + _ => binding.glass.ior = 1.7, + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_exact_repeat_preserves_existing_cpu_permission_disabled_state_and_values() { + let mut h = fixture(); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + h.app.render_workspace.view.materials.bindings[0].enabled = false; + h.app.render_workspace.view.materials.enabled = false; + let before = format!("{:?}", h.app.render_workspace.view.materials); + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + } + + #[test] + fn library_bridge_respects_authoring_and_cpu_target_caps_without_activating_other_bindings() { + for (method, count, active) in [(ImageMethod::GpuRaytrace, 128, false), (ImageMethod::CpuRaytrace, 8, true)] { + let mut h = fixture(); + h.app.render_workspace.view.method = method; + let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|t| t.name == "Optics").unwrap(); + for i in 0..count { + let mut other = target.clone(); + other.name = format!("Other{i}"); + let mut binding = materials::Binding::new(other, &h.app); + binding.glass_enabled = active; + h.app.render_workspace.view.materials.bindings.push(binding); + } + let before = format!("{:?}", h.app.render_workspace.view.materials); + assert!(library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").is_err()); + assert_eq!(format!("{:?}", h.app.render_workspace.view.materials), before); + } + } + + #[test] + fn library_bridge_keeps_closed_thin_and_strict_cpu_choices_explicit_without_a_transport_claim() { + let mut h = fixture(); + h.app.render_workspace.view.raytrace.dielectric_transport = solidcraft_engine::render::job::CpuDielectricTransport::StrictTir; + h.app.render_workspace.view.draft.exposure_ev = 1.25; + h.app.render_workspace.view.cpu.environment = cpu::Environment::Constant; + h.app.render_workspace.view.cpu.color = [0.25, 0.5, 0.75]; + h.app.render_workspace.view.cpu.intensity = 2.0; + library::stage_glass(&mut h.app, "starter.glass.low-iron-clear").unwrap(); + assert!(runtime_image_request(&h.app, false).is_err()); + h.app.render_workspace.view.materials.bindings[0].cpu_optics = true; + assert!(runtime_image_request(&h.app, false).is_err(), "Closed is not silently certified Box"); + h.app.render_workspace.view.materials.bindings[0].glass.boundary = materials::Boundary::Box; + let wire = runtime_image_request(&h.app, false).unwrap(); + assert_eq!(wire["raytrace"]["dielectric_transport"], "strict_tir"); + assert_eq!(wire["raytrace"]["dielectrics"][0]["ior"], 1.5); + assert_eq!(wire["raytrace"]["dielectrics"][0]["boundary"], "closed_box"); + assert_eq!(wire["raytrace"]["exposure_ev"], 1.25); + assert_eq!(wire["settings"]["exposure_ev"], 0.0); + assert_eq!(wire["raytrace"]["environment"]["color"], json!([0.25, 0.5, 0.75])); + assert_eq!(wire["raytrace"]["environment"]["intensity"], 2.0); + assert!(setups::snapshot(&h.app).is_err(), "transient staging never becomes saved CPU optics"); + // This checks routing only. A real StrictTir LimitExceeded remains FAIL for G02-C. + } + + #[test] + fn clicked_library_glass_action_reaches_existing_body_editor_and_never_reports_applied() { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":1800})); + let mut view = std::mem::take(&mut h.app.render_workspace.view.library); + library::choose(&mut h.app, &mut view, "appearances", "starter.glass.low-iron-clear").unwrap(); + h.app.render_workspace.view.library = view; + h.frames(3); + let doc = h.app.session.doc.clone(); + h.step(&json!({"click":{"handle":"render:library:prepare-glass"}})).unwrap(); + assert_eq!(h.app.render_workspace.view.materials.bindings.len(), 1); + assert!(!h.app.render_workspace.view.materials.bindings[0].cpu_optics); + assert_eq!(h.app.render_workspace.view.materials.bindings[0].glass.boundary, materials::Boundary::Closed); + assert_eq!(h.app.render_workspace.view.inspector.page, inspector::Page::Appearance); + assert!( + matches!(&h.app.render_workspace.view.selection, RenderSelection::Object(items) if matches!(items.as_slice(), [Sel::Body {name}] if name == "Optics")) + ); + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(h.app.status.as_ref().unwrap().0, h.app.tr("render.glass_library_prepared")); + assert_ne!(h.app.status.as_ref().unwrap().0, h.app.tr("render.library_applied")); + } + + #[test] + fn library_bridge_messages_cover_every_current_delivered_locale() { + let messages: Value = serde_json::from_str(include_str!("../../../assets/locales/pending/render-glass-library-route.json")).unwrap(); + for locale in ["en", "es", "de", "ko", "ar", "he", "ja", "vi", "zh"] { + for id in [ + "render.glass_library_conflict", + "render.glass_library_edit", + "render.glass_library_help", + "render.glass_library_method", + "render.glass_library_prepared", + ] { + assert!(messages[locale][id].as_str().is_some_and(|s| !s.is_empty()), "{locale}/{id}"); + } + } + } +} + +#[test] +fn cpu_partial_coverage_crosses_u16_boundary_without_relaxing_alpha_or_sample_frontier() { + for count in [65_535, 65_536, 1_048_576] { + assert!(interactive::validate_partial_pixel(count, count, Color32::BLACK, [40, 80, 120]).is_ok()); + assert!(interactive::validate_partial_pixel(count, count + 1, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(count, count, Color32::TRANSPARENT, [40, 80, 120]).is_err()); + assert_eq!(interactive::partial_sample_count(count, 0, 0, 1, 1_048_576).unwrap(), count); + } + assert!(interactive::validate_partial_pixel(0, 0, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(65_536, 0, Color32::BLACK, [40, 80, 120]).is_err()); + assert!(interactive::validate_partial_pixel(65_536, 0, Color32::from_rgb(40, 80, 120), [40, 80, 120]).is_ok()); + assert!(interactive::partial_sample_count(65_536, 1, 0, 1, 65_536).is_err()); +} + +#[test] +fn cpu_progressive_editor_preserves_high_intent_without_resizing_or_changing_profile_seed_or_mode() { + use solidcraft_engine::render::job::{CpuBudget, CpuProgressiveOptions}; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.raytrace.budget = CpuBudget::Workstation; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: u32::MAX }); + let doc = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + for budget in [CpuBudget::Workstation, CpuBudget::Compact, CpuBudget::Studio] { + h.app.render_workspace.view.raytrace.budget = budget; + let before = json!(h.app.render_workspace.view.raytrace); + let ctx = egui::Context::default(); + let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + assert!(cpu::progressive_controls(&mut h.app, ui)); + }); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before, "painting cannot clamp retained intent to a different profile"); + assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), (1, 1)); + assert_eq!(cpu::validate_progressive_image(&h.app).is_ok(), budget == CpuBudget::Workstation); + } + assert!(Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); +} + +// Request/consumer coverage only. Real native per-pass presentation remains +// mandatory acceptance; see the archived unsupported cooperative-host fixture. +#[test] +fn cpu_progressive_request_keeps_explicit_target_seed_without_claiming_native_pass_presentation() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 1; + h.app.render_workspace.view.draft.height = 1; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 4, seed: 741 }); + let document = h.app.session.doc.clone(); + let before = json!(h.app.render_workspace.view.raytrace); + let request = interactive_request(&h.app).unwrap(); + assert_eq!(request["raytrace"]["progressive"]["samples_per_pixel"], 4); + assert_eq!(request["raytrace"]["progressive"]["seed"], 741); + assert_ne!(request["progressive"], json!(true), "CPU intent cannot select a registered GPU executor"); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation() { + use solidcraft_engine::render::job::{CpuProgressiveOptions, Phase}; + use std::{sync::mpsc, time::Duration}; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_real_explicit_pass_target_png_and_seed_survive_cache_pause_and_final_isolation") { + return; + } + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); + let before = json!(h.app.render_workspace.view.raytrace); + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + // Withhold only the real worker reply. All frame bytes come from the renderer. + let mut pending = h.app.render_workspace.interactive.pending.take().unwrap(); + let reply = pending.receiver.recv_timeout(Duration::from_secs(60)).unwrap(); + assert!(matches!(&reply, Ok(true)), "{reply:?}"); + let job = interactive::test_current(&h.app).unwrap().unwrap(); + let status = job.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 })); + let frame = job.frame().unwrap().unwrap(); + assert_eq!(frame.info.executor.as_str(), "cpu-raytrace"); + assert!(!frame.png().is_empty()); + let (sender, receiver) = mpsc::channel(); + pending.receiver = receiver; + h.app.render_workspace.interactive.pending = Some(pending); + sender.send(reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); + assert_eq!((cached.job, samples, complete), (job.id(), 31, true)); + assert_eq!(cached.png_sha256, frame.info.png_sha256); + let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); + let egui::ImageData::Color(pixels) = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; + assert_eq!(pixels.size, [png.width() as usize, png.height() as usize]); + assert!( + pixels.pixels.iter().zip(png.pixels()).all(|(actual, rgba)| *actual == Color32::from_rgba_unmultiplied(rgba[0], rgba[1], rgba[2], rgba[3])) + ); + output.textures_delta.clear(); + assert_eq!(json!(h.app.render_workspace.view.raytrace), before); + h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 47, seed: 999 }); + let expected = crate::i18n::format("render.interactive_samples", &[("done", "31"), ("total", "31")]); + let controls = h.ctx.run_ui(egui::RawInput::default(), |ui| interactive::controls(&mut h.app, ui)); + assert!(crate::test_support::text_shapes(&controls).any(|shape| shape.galley.text() == expected)); + assert_eq!(interactive::test_cache(&h.app).unwrap().3, texture); + interactive_assert_final_export_isolation(&mut h, &job); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} + +#[test] +fn interactive_retention_skip_inspect_is_null_without_an_admitted_capture() { + let h = Harness::new(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off() { + let mut h = interactive_ui_fixture(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); + if !interactive_test_cpu_branch(&mut h, "interactive_retention_skip_inspect_preserves_real_zero_and_clears_after_off") { + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null(), "enabling without an admitted job cannot fabricate zero"); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + let captured = held.job.status().unwrap(); + assert_eq!(captured.cpu_preview_retention_skips, 0); + assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(captured.cpu_preview_retention_skips)); + interactive_assert_final_export_isolation(&mut h, &held.job); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + output.textures_delta.clear(); + assert_eq!(interactive::inspect(&h.app)["cpu_preview_retention_skips"], json!(0)); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); + assert!(interactive::inspect(&h.app)["cpu_preview_retention_skips"].is_null()); +} + +// Typed consumer state only: this texture is input to the absent-slot policy. +// It is not a renderer PNG, a CPU admission fixture, or per-pass UI acceptance. +fn cpu_preview_consumer_fixture(ctx: &egui::Context) -> (State, JobId, solidcraft_engine::render::job::JobStatus) { + use solidcraft_engine::render::job::{ + AlphaConvention, ColourEncoding, CpuProgressiveOptions, FrameInfo, ImageRequest, JobOptions, JobStatus, Phase, Progress, RaytraceOptions, + }; + use solidcraft_engine::render::{BackendId, ExecutorId, RenderMode, RenderOperation, RenderProfile, ResolvedRequest}; + let job = JobId { session: 9012, serial: 1, generation: 1 }; + let backend = BackendId::new("consumer-fixture").unwrap(); + let executor = ExecutorId::new("consumer-fixture").unwrap(); + let frame = FrameInfo { + job, + scene_generation: 19, + backend: backend.clone(), + executor: executor.clone(), + width: 1, + height: 1, + encoding: ColourEncoding::Srgb, + alpha: AlphaConvention::Straight, + png_bytes: 0, + png_sha256: String::new(), + }; + let texture = + ctx.load_texture("consumer-only-input", egui::ColorImage::new([1, 1], vec![Color32::from_rgb(40, 80, 120)]), egui::TextureOptions::LINEAR); + let mut state = State::default(); + state.view.job = Some(job); + state.preview_image = Some(PreviewImage { info: PreviewInfo { frame_sequence: 2, samples_per_pixel: 2, frame }, image: Ok(texture) }); + let request = ImageRequest { + cpu_progressive_every_pass: true, + raster_exposure_ev: 0.0, + raster_lights: None, + raster_punctual_lights: None, + raster_area_lights: None, + studio_weights: None, + environment: None, + textures: None, + integrator: Integrator::Raytrace, + raytrace: Some(RaytraceOptions { + primary_samples: 1, + progressive: Some(CpuProgressiveOptions { samples_per_pixel: 7, seed: 741 }), + ..Default::default() + }), + camera: Default::default(), + width: 1, + height: 1, + background: [40, 80, 120], + transparent_background: false, + }; + let status = JobStatus { + cpu_preview_retention_skips: 1, + punctual_diagnostics: None, + presentation: None, + sampling: None, + linear_master: None, + preview: None, + textures: None, + options: JobOptions::default(), + environment: None, + job, + scene_generation: 19, + request, + resolved: ResolvedRequest { + backend, + executor, + profile: RenderProfile { mode: RenderMode::Preview, operation: RenderOperation::Image, formats: Vec::new(), features: Vec::new() }, + width: 1, + height: 1, + format: None, + estimated_scratch_bytes: 0, + warnings: Vec::new(), + }, + progress: Progress { phase: Phase::Running, done: 3, total: 7 }, + error: None, + frame: None, + }; + (state, job, status) +} + +#[test] +fn cpu_missing_snapshot_consumer_keeps_exact_pixels_identity_and_pass_only_for_certified_live_capture() { + let ctx = egui::Context::default(); + let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); + let before = state.preview_image.as_ref().unwrap(); + let texture = before.image.as_ref().unwrap().id(); + let identity = (before.info.frame.job, before.info.frame.scene_generation, before.info.frame_sequence, before.info.samples_per_pixel); + status.progress.done = 4; + reconcile_missing_cpu_preview(&mut state, job, Some(&status)); + let kept = state.preview_image.as_ref().unwrap(); + assert_eq!(kept.image.as_ref().unwrap().id(), texture); + assert_eq!((kept.info.frame.job, kept.info.frame.scene_generation, kept.info.frame_sequence, kept.info.samples_per_pixel), identity); + assert_eq!(kept.info.samples_per_pixel, 2, "producer progress cannot relabel accepted pixels"); + assert!(state.view.completed.is_none(), "retention cannot manufacture final authority"); +} + +#[test] +fn cpu_missing_snapshot_consumer_clears_wrong_capture_cancel_error_final_and_lookup_failure() { + use solidcraft_engine::render::job::{ErrorCode, JobError, Phase}; + let ctx = egui::Context::default(); + for case in 0..13 { + let (mut state, job, mut status) = cpu_preview_consumer_fixture(&ctx); + let mut lookup_ok = true; + match case { + 0 => status.job.serial += 1, + 1 => status.scene_generation += 1, + 2 => status.request.width += 1, + 3 => status.progress.phase = Phase::Cancelling, + 4 => status.progress.phase = Phase::Cancelled, + 5 => status.progress.phase = Phase::Failed, + 6 => status.progress.phase = Phase::Completed, + 7 => status.error = Some(JobError::new(ErrorCode::Internal, "consumer fixture status error")), + 8 => status.frame = Some(state.preview_image.as_ref().unwrap().info.frame.clone()), + 9 => status.cpu_preview_retention_skips = 0, + 10 => status.request.raytrace.as_mut().unwrap().progressive = None, + 11 => state.preview_image.as_mut().unwrap().image = Err("consumer fixture decode error".into()), + 12 => lookup_ok = false, + _ => unreachable!(), + } + reconcile_missing_cpu_preview(&mut state, job, lookup_ok.then_some(&status)); + assert!(state.preview_image.is_none(), "case {case}"); + assert!(state.view.completed.is_none()); + } + let mut h = Harness::new(); + let (mut state, job, _) = cpu_preview_consumer_fixture(&ctx); + state.view.job = None; + h.app.render_workspace = state; + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + let (state, _, _) = cpu_preview_consumer_fixture(&ctx); + h.app.render_workspace = state; + assert!(h.app.session.render_job_handle(job).is_err(), "consumer fixture is deliberately not an admitted job"); + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); +} + + +#[test] +fn cpu_capture_policy_preferences_preserve_typed_setup_final_intent_and_independent_sampling_copy() { + use solidcraft_engine::render::job::CpuProgressiveOptions; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); + let original_options = json!(h.app.render_workspace.view.raytrace); + let saved = setups::snapshot(&h.app).unwrap(); + let document = h.app.session.doc.clone(); + let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); + for each_pass in [true, false] { + for preserve_sampling in [true, false] { + h.app.preferences.render_cpu_progressive_every_pass = each_pass; + h.app.preferences.render_cpu_interactive_explicit_sampling = preserve_sampling; + let final_request = image_request(&h.app).unwrap(); + assert_eq!(final_request["settings"], json!(saved), "portable settings.job stays intact"); + assert!(final_request.get("raytrace").is_none(), "no contradictory parallel runtime CPU options"); + assert_eq!(final_request.get("cpu_progressive_every_pass"), (!each_pass).then_some(&json!(false))); + let interactive = interactive_request(&h.app).unwrap(); + assert_eq!(interactive["raytrace"]["progressive"]["samples_per_pixel"], if preserve_sampling { 31 } else { 16 }); + assert_eq!(interactive["raytrace"]["progressive"]["seed"], if preserve_sampling { 741 } else { 0 }); + assert_eq!(interactive.get("cpu_progressive_every_pass"), (!each_pass).then_some(&json!(false))); + assert_eq!(interactive["settings"]["width"], 16); + assert_eq!(interactive["settings"]["height"], 16); + let frozen_command = interactive.clone(); + h.app.preferences.render_cpu_progressive_every_pass = !each_pass; + let later_command = interactive_request(&h.app).unwrap(); + assert_ne!(frozen_command, later_command, "the exact Value identity carries the policy"); + assert_eq!(frozen_command, interactive, "an issued command copy cannot follow a later preference edit"); + h.app.preferences.render_cpu_progressive_every_pass = each_pass; + assert_eq!(json!(h.app.render_workspace.view.raytrace), original_options); + assert_eq!(setups::snapshot(&h.app).unwrap(), saved); + } + } + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); +} + +#[test] +fn cpu_capture_cadence_is_absent_for_single_raster_gpu_and_present_for_derived_interactive_progressive() { + let mut h = Harness::new(); + h.app.preferences.render_cpu_progressive_every_pass = false; + h.app.preferences.render_cpu_interactive_explicit_sampling = false; + h.app.render_workspace.view.draft.width = 16; + h.app.render_workspace.view.draft.height = 16; + for method in [ImageMethod::Raster, ImageMethod::GpuRaytrace, ImageMethod::CpuRaytrace] { + h.app.render_workspace.view.method = method; + h.app.render_workspace.view.raytrace.progressive = None; + let request = image_request(&h.app).unwrap(); + assert!(request.get("cpu_progressive_every_pass").is_none()); + } + h.app.render_workspace.view.raytrace.primary_samples = 16; + let fixed_editor = json!(h.app.render_workspace.view.raytrace); + let preview_request = interactive_request(&h.app).unwrap(); + assert_eq!(preview_request["cpu_progressive_every_pass"], false); + assert!(preview_request["raytrace"].get("progressive").is_none(), "engine owns Fixed-to-Interactive conversion"); + assert_eq!(preview_request["raytrace"]["primary_samples"], 16); + assert_eq!(json!(h.app.render_workspace.view.raytrace), fixed_editor); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn legacy_interactive_sampling_keeps_reduced_preview_admission_without_final_budget_or_hostile_repair() { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, interactive::cpu_request}; + let mut h = Harness::new(); + h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; + h.app.render_workspace.view.draft.width = 3840; + h.app.render_workspace.view.draft.height = 2160; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); + h.app.preferences.render_cpu_progressive_every_pass = false; + h.app.preferences.render_cpu_interactive_explicit_sampling = false; + let editor = json!(h.app.render_workspace.view.raytrace); + assert!(image_request(&h.app).is_err(), "the original final dimensions still exceed Compact progressive admission"); + let wire = interactive_request(&h.app).unwrap(); + assert_eq!((wire["settings"]["width"].as_u64(), wire["settings"]["height"].as_u64()), (Some(3840), Some(2160))); + let request: ImageRequest = serde_json::from_value(json!({ + "integrator":"raytrace", "camera":h.app.cam, "width":3840, "height":2160, + "background":h.app.render_workspace.view.draft.background, "transparent_background":false, + "raytrace":wire["raytrace"], "cpu_progressive_every_pass":wire["cpu_progressive_every_pass"] + })).unwrap(); + let preview = cpu_request(&request).unwrap(); + assert_eq!((preview.width, preview.height), (1024, 576)); + assert!(!preview.cpu_progressive_every_pass, "the same canonical cadence flag survives derived capture"); + assert_eq!(preview.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); + assert_eq!(json!(h.app.render_workspace.view.raytrace), editor); + h.app.preferences.render_cpu_interactive_explicit_sampling = true; + let explicit = interactive_request(&h.app).unwrap(); + let mut explicit_request = request.clone(); + explicit_request.raytrace = Some(serde_json::from_value(explicit["raytrace"].clone()).unwrap()); + assert!(cpu_request(&explicit_request).is_err(), "31SPP exceeds the reduced image's original camera-sample envelope; never downgrade it"); + h.app.preferences.render_cpu_interactive_explicit_sampling = false; + h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().samples_per_pixel = 0; + assert!(interactive_request(&h.app).is_err(), "legacy preview cannot repair an invalid numerical request"); + assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_snapshot_policy_and_sampling_stay_captured_after_later_preference_edits() { + use solidcraft_engine::render::job::{CpuProgressiveOptions, Phase, interactive::VisualRevision}; + use std::time::Duration; + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_snapshot_policy_and_sampling_stay_captured_after_later_preference_edits") { + return; + } + h.app.render_workspace.view.draft.width = 4; + h.app.render_workspace.view.draft.height = 4; + h.app.render_workspace.view.raytrace.primary_samples = 1; + h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 741 }); + h.app.preferences.render_cpu_progressive_every_pass = false; + h.app.preferences.render_cpu_interactive_explicit_sampling = false; + let captured_value = interactive_request(&h.app).unwrap(); + let context = h.app.session.interactive_render().unwrap(); + context.enable(VisualRevision { scene_generation: h.app.session.revision, visual_revision: 1 }, Duration::ZERO).unwrap(); + let ticket = context.capture(Duration::from_millis(201)).unwrap().unwrap(); + let snapshot = context.snapshot(&h.app.session, ticket, &captured_value).unwrap(); + h.app.preferences.render_cpu_progressive_every_pass = true; + h.app.preferences.render_cpu_interactive_explicit_sampling = true; + assert_ne!(interactive_request(&h.app).unwrap(), captured_value); + assert!(snapshot.run().unwrap(), "the real snapshot prepares its frozen command Value"); + let handle = context.current().unwrap().unwrap(); + let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); + assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); + assert!(!status.request.cpu_progressive_every_pass); + assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); + assert_eq!(serde_json::to_value(&status.request).unwrap()["cpu_progressive_every_pass"], false, "prepared metadata keeps the canonical false value"); + assert!(handle.frame().unwrap().is_some()); + assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 741 })); + interactive_assert_final_export_isolation(&mut h, &handle); + context.disable().unwrap(); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn interactive_cadence_preference_edit_invalidates_real_capture_through_existing_request_identity() { + let mut h = interactive_ui_fixture(); + if !interactive_test_cpu_branch(&mut h, "interactive_cadence_preference_edit_invalidates_real_capture_through_existing_request_identity") { + return; + } + let epoch = interactive::test_clock(&h.app).as_secs_f64(); + h.app.run("render.interactive", json!({"action":"on"})).unwrap(); + interactive_clear_acceptance_frame(&mut h, epoch, true); + interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); + let held = interactive_hold_real_completed_callback(&mut h); + held.sender.send(held.reply).unwrap(); + let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); + assert!(painted); + output.textures_delta.clear(); + let old_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); + let old_request = interactive_request(&h.app).unwrap(); + h.app.preferences.render_cpu_progressive_every_pass = false; + interactive_control_frame(&mut h, epoch + 0.4, vec![]); + assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > old_visual); + assert!(interactive::test_current(&h.app).unwrap().is_none(), "existing edit path releases/cancels its owned capture"); + assert!(interactive::test_cache(&h.app).is_none()); + assert!(!h.app.render_workspace.interactive.pending(), "before_paint cannot launch a replacement"); + assert_ne!(interactive_request(&h.app).unwrap(), old_request); + assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); + // This real source completed before the edit; this test does not claim to + // observe cancellation of an in-flight renderer or every physical repaint. + assert!(held.job.frame().unwrap().is_some()); + h.app.run("render.interactive", json!({"action":"off"})).unwrap(); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_thumbnails.rs b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_thumbnails.rs new file mode 100644 index 000000000..500303498 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/candidate/crates/ui-egui/src/render_workspace_thumbnails.rs @@ -0,0 +1,189 @@ +//! Ephemeral shot previews. One cancellable CPU task; no host, job identity or document edits. +use std::collections::BTreeMap; +use std::hash::{Hash, Hasher}; + +use crate::SolveApp; +use solidcraft_engine::render::{Camera, job::CancelToken}; + +pub(super) const LIMIT: usize = 16; +#[cfg(not(target_arch = "wasm32"))] +const SIZE: [u32; 2] = [104, 60]; + +// Cancellation is cooperative. Keep a single process-wide worker permit so rapid tab/document +// changes cannot accumulate detached workers while the previous task finishes its bounded step. +#[cfg(not(target_arch = "wasm32"))] +static WORKER_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(not(target_arch = "wasm32"))] +struct WorkerPermit; +#[cfg(not(target_arch = "wasm32"))] +impl Drop for WorkerPermit { + fn drop(&mut self) { + WORKER_ACTIVE.store(false, std::sync::atomic::Ordering::Release); + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(super) struct Key { + pub name: String, + revision: u64, + scene: u64, + camera: u64, +} + +impl Key { + pub(super) fn new(name: String, revision: u64, scene: u64, camera: Camera) -> Self { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + // Camera's complete serialized numerical intent, including roll, projection and up axis. + if let Ok(bytes) = serde_json::to_vec(&camera) { + bytes.hash(&mut hash); + } + Self { name, revision, scene, camera: hash.finish() } + } +} + +#[derive(Default)] +pub(super) struct Cache { + pub entries: BTreeMap>, + visible: Vec, + pending: Option, +} +struct Pending { + key: Key, + cancel: CancelToken, + result: std::sync::mpsc::Receiver>, +} +impl Drop for Cache { + fn drop(&mut self) { + if let Some(pending) = &self.pending { + pending.cancel.cancel(); + } + } +} +impl Cache { + pub fn show(&mut self, names: Vec, ctx: &egui::Context) { + let names = names.into_iter().take(LIMIT).collect::>(); + if self.visible != names { + self.visible = names; + ctx.request_repaint(); + } + } + + pub fn texture(&self, name: &str) -> Option { + self.entries.iter().find(|(key, _)| key.name == name).and_then(|(_, value)| value.as_ref().map(egui::TextureHandle::id)) + } + + pub fn retain(&mut self, keys: &[Key]) { + self.entries.retain(|key, _| keys.iter().take(LIMIT).any(|wanted| wanted == key)); + if let Some(pending) = &self.pending + && !keys.iter().take(LIMIT).any(|key| key == &pending.key) + { + // Keep the receiver until the worker exits: invalidation cannot spawn extra workers. + pending.cancel.cancel(); + } + } + + fn poll(&mut self, ctx: &egui::Context, keys: &[Key]) { + let Some(pending) = &self.pending else { return }; + let image = match pending.result.try_recv() { + Ok(image) => image, + Err(std::sync::mpsc::TryRecvError::Empty) => { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => None, + }; + if let Some(pending) = self.pending.take() + && keys.iter().take(LIMIT).any(|key| key == &pending.key) + && !pending.cancel.is_cancelled() + { + self.entries.insert(pending.key, image.map(|image| ctx.load_texture("shot_thumbnail", image, egui::TextureOptions::LINEAR))); + } + } +} + +pub(super) fn refresh(app: &mut SolveApp, ctx: &egui::Context) { + let mut scene = std::collections::hash_map::DefaultHasher::new(); + app.session.visibility.hidden_bodies.hash(&mut scene); + app.session.visibility.hidden_occurrences.hash(&mut scene); + (std::sync::Arc::as_ptr(&app.session.world_state()) as usize).hash(&mut scene); + let scene = scene.finish(); + let mut keys = Vec::new(); + for name in std::iter::once(&app.render_workspace.view.name) + .chain(app.render_workspace.thumbnails.visible.iter()) + .chain(app.session.doc.render.setups.keys()) + { + if keys.len() == LIMIT { + break; + } + if keys.iter().any(|key: &Key| &key.name == name) { + continue; + } + if let Some(setup) = app.session.doc.render.setups.get(name) { + keys.push(Key::new(name.clone(), app.session.revision, scene, setup.camera)); + } + } + let cache = &mut app.render_workspace.thumbnails; + cache.retain(&keys); + cache.poll(ctx, &keys); + if cache.pending.is_some() { + return; + } + let Some(key) = keys.into_iter().find(|key| !cache.entries.contains_key(key)) else { return }; + #[cfg(not(target_arch = "wasm32"))] + { + if WORKER_ACTIVE.compare_exchange(false, true, std::sync::atomic::Ordering::Acquire, std::sync::atomic::Ordering::Relaxed).is_err() { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + let permit = WorkerPermit; + let Some(setup) = app.session.doc.render.setups.get(&key.name) else { return }; + let request = solidcraft_engine::render::job::ImageRequest { + cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, + camera: setup.camera, + width: SIZE[0], + height: SIZE[1], + background: setup.background, + transparent_background: false, + integrator: Default::default(), + raytrace: None, + environment: None, + textures: None, + }; + let scene = solidcraft_engine::product_scene::extract(&app.session); + let cancel = CancelToken::default(); + let worker_cancel = cancel.clone(); + let (send, result) = std::sync::mpsc::sync_channel(1); + let worker = std::thread::Builder::new().name("shot-thumbnail".into()).spawn(move || { + let _permit = permit; + let image = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let scene = scene.ok()?; + let mut task = solidcraft_engine::render::job::ImageTask::new(scene, request, worker_cancel).ok()?; + loop { + match task.step(1024).ok()? { + solidcraft_engine::render::job::TaskPoll::Pending(_) => {} + solidcraft_engine::render::job::TaskPoll::Complete(png) => { + let image = image::load_from_memory(&png).ok()?.to_rgba8(); + return Some(egui::ColorImage::from_rgba_unmultiplied([SIZE[0] as usize, SIZE[1] as usize], image.as_raw())); + } + } + } + })) + .ok() + .flatten(); + let _ = send.send(image); + }); + if worker.is_ok() { + app.render_workspace.thumbnails.pending = Some(Pending { key, cancel, result }); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } else { + app.render_workspace.thumbnails.entries.insert(key, None); + } + } + #[cfg(target_arch = "wasm32")] + cache.entries.insert(key, None); +} diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/delta-LF-review.patch b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/delta-LF-review.patch new file mode 100644 index 000000000..91d6f7ed9 --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/delta-LF-review.patch @@ -0,0 +1,285 @@ +--- a/crates/render/src/job/interactive.rs ++++ b/crates/render/src/job/interactive.rs +@@ -296,6 +296,7 @@ + + fn request(options: RaytraceOptions) -> ImageRequest { + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +--- a/crates/ui-egui/src/render_workspace.rs ++++ b/crates/ui-egui/src/render_workspace.rs +@@ -898,7 +898,19 @@ + + /// Pure request construction is shared with offline setup editing; host checks stay above. + fn image_request(app: &SolveApp) -> Result { +- light::filter_request(app, raw_image_request(app)?) ++ let request = light::filter_request(app, raw_image_request(app)?)?; ++ cpu_checkpoint_policy(app, request, app.render_workspace.view.raytrace.progressive.is_some()) ++} ++ ++/// One transient command flag for capture and identity, never saved setup intent. ++fn cpu_checkpoint_policy(app: &SolveApp, mut request: serde_json::Value, progressive: bool) -> Result { ++ if app.render_workspace.view.method == ImageMethod::CpuRaytrace && progressive && !app.preferences.render_cpu_progressive_every_pass { ++ request ++ .as_object_mut() ++ .ok_or_else(|| app.tr("render.error_provisional_identity").to_string())? ++ .insert("cpu_progressive_every_pass".into(), json!(false)); ++ } ++ Ok(request) + } + + fn raw_image_request(app: &SolveApp) -> Result { +@@ -915,7 +927,9 @@ + if app.render_workspace.view.method != ImageMethod::CpuRaytrace { + return Err(app.tr("render.interactive_requires_cpu").into()); + } +- light::filter_request(app, runtime_image_request(app, true)?) ++ let request = light::filter_request(app, runtime_image_request(app, true)?)?; ++ // Interactive always becomes CPU progressive, including a Fixed final editor. ++ cpu_checkpoint_policy(app, request, true) + } + + /// The existing runtime branch, shared without changing Final Check/Start policy. +--- a/crates/ui-egui/src/render_workspace_cpu.rs ++++ b/crates/ui-egui/src/render_workspace_cpu.rs +@@ -369,7 +369,20 @@ + { + return Err(app.tr("render.cpu_binding_stale").to_string()); + } +- params_with_binding_policy(app, params, binding_interactive_current) ++ params_with_binding_policy(app, params, binding_interactive_current)?; ++ if !app.preferences.render_cpu_interactive_explicit_sampling { ++ let options = params ++ .get_mut("raytrace") ++ .and_then(Value::as_object_mut) ++ .ok_or_else(|| app.tr("render.error_provisional_identity").to_string())?; ++ // The original request was validated above. Only an explicit progressive ++ // object is replaced; Fixed stays Fixed until the engine's existing ++ // preview conversion applies primary/reflection1 and the fallback16/0. ++ if options.get("progressive").is_some_and(|value| !value.is_null()) { ++ options.insert("progressive".into(), json!(solidcraft_engine::render::job::CpuProgressiveOptions::default())); ++ } ++ } ++ Ok(()) + } + + fn params_with_binding_policy(app: &SolveApp, params: &mut Value, current: fn(&SolveApp, &str) -> bool) -> Result<(), String> { +--- a/crates/ui-egui/src/render_workspace_tests.rs ++++ b/crates/ui-egui/src/render_workspace_tests.rs +@@ -1211,6 +1211,7 @@ + let mut task = ImageTask::new( + scene, + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -3622,6 +3623,7 @@ + fn large_image_display_uses_captured_profile_and_keeps_export_pixels_unchanged() { + use solidcraft_engine::render::job::{CpuBudget, ImageRequest, RaytraceOptions}; + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -8613,6 +8615,7 @@ + fn partial_png_contract_request() -> solidcraft_engine::render::job::ImageRequest { + use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, RaytraceOptions}; + ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, +@@ -11484,6 +11487,7 @@ + state.view.job = Some(job); + state.preview_image = Some(PreviewImage { info: PreviewInfo { frame_sequence: 2, samples_per_pixel: 2, frame }, image: Ok(texture) }); + let request = ImageRequest { ++ cpu_progressive_every_pass: true, + raster_exposure_ev: 0.0, + raster_lights: None, + raster_punctual_lights: None, +@@ -11588,3 +11592,172 @@ + cache_preview_image(&mut h.app, &ctx); + assert!(h.app.render_workspace.preview_image.is_none()); + } ++ ++ ++#[test] ++fn cpu_capture_policy_preferences_preserve_typed_setup_final_intent_and_independent_sampling_copy() { ++ use solidcraft_engine::render::job::CpuProgressiveOptions; ++ let mut h = Harness::new(); ++ h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; ++ h.app.render_workspace.view.draft.width = 16; ++ h.app.render_workspace.view.draft.height = 16; ++ h.app.render_workspace.view.raytrace.primary_samples = 1; ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); ++ let original_options = json!(h.app.render_workspace.view.raytrace); ++ let saved = setups::snapshot(&h.app).unwrap(); ++ let document = h.app.session.doc.clone(); ++ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty()); ++ for each_pass in [true, false] { ++ for preserve_sampling in [true, false] { ++ h.app.preferences.render_cpu_progressive_every_pass = each_pass; ++ h.app.preferences.render_cpu_interactive_explicit_sampling = preserve_sampling; ++ let final_request = image_request(&h.app).unwrap(); ++ assert_eq!(final_request["settings"], json!(saved), "portable settings.job stays intact"); ++ assert!(final_request.get("raytrace").is_none(), "no contradictory parallel runtime CPU options"); ++ assert_eq!(final_request.get("cpu_progressive_every_pass"), (!each_pass).then_some(&json!(false))); ++ let interactive = interactive_request(&h.app).unwrap(); ++ assert_eq!(interactive["raytrace"]["progressive"]["samples_per_pixel"], if preserve_sampling { 31 } else { 16 }); ++ assert_eq!(interactive["raytrace"]["progressive"]["seed"], if preserve_sampling { 741 } else { 0 }); ++ assert_eq!(interactive.get("cpu_progressive_every_pass"), (!each_pass).then_some(&json!(false))); ++ assert_eq!(interactive["settings"]["width"], 16); ++ assert_eq!(interactive["settings"]["height"], 16); ++ let frozen_command = interactive.clone(); ++ h.app.preferences.render_cpu_progressive_every_pass = !each_pass; ++ let later_command = interactive_request(&h.app).unwrap(); ++ assert_ne!(frozen_command, later_command, "the exact Value identity carries the policy"); ++ assert_eq!(frozen_command, interactive, "an issued command copy cannot follow a later preference edit"); ++ h.app.preferences.render_cpu_progressive_every_pass = each_pass; ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), original_options); ++ assert_eq!(setups::snapshot(&h.app).unwrap(), saved); ++ } ++ } ++ assert!(Arc::ptr_eq(&document, &h.app.session.doc)); ++ assert_eq!(history, (h.app.session.revision, h.app.session.undo.len(), h.app.session.is_dirty())); ++} ++ ++#[test] ++fn cpu_capture_cadence_is_absent_for_single_raster_gpu_and_present_for_derived_interactive_progressive() { ++ let mut h = Harness::new(); ++ h.app.preferences.render_cpu_progressive_every_pass = false; ++ h.app.preferences.render_cpu_interactive_explicit_sampling = false; ++ h.app.render_workspace.view.draft.width = 16; ++ h.app.render_workspace.view.draft.height = 16; ++ for method in [ImageMethod::Raster, ImageMethod::GpuRaytrace, ImageMethod::CpuRaytrace] { ++ h.app.render_workspace.view.method = method; ++ h.app.render_workspace.view.raytrace.progressive = None; ++ let request = image_request(&h.app).unwrap(); ++ assert!(request.get("cpu_progressive_every_pass").is_none()); ++ } ++ h.app.render_workspace.view.raytrace.primary_samples = 16; ++ let fixed_editor = json!(h.app.render_workspace.view.raytrace); ++ let preview_request = interactive_request(&h.app).unwrap(); ++ assert_eq!(preview_request["cpu_progressive_every_pass"], false); ++ assert!(preview_request["raytrace"].get("progressive").is_none(), "engine owns Fixed-to-Interactive conversion"); ++ assert_eq!(preview_request["raytrace"]["primary_samples"], 16); ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), fixed_editor); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn legacy_interactive_sampling_keeps_reduced_preview_admission_without_final_budget_or_hostile_repair() { ++ use solidcraft_engine::render::job::{CpuProgressiveOptions, ImageRequest, interactive::cpu_request}; ++ let mut h = Harness::new(); ++ h.app.render_workspace.view.method = ImageMethod::CpuRaytrace; ++ h.app.render_workspace.view.draft.width = 3840; ++ h.app.render_workspace.view.draft.height = 2160; ++ h.app.render_workspace.view.raytrace.primary_samples = 1; ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 31, seed: 741 }); ++ h.app.preferences.render_cpu_progressive_every_pass = false; ++ h.app.preferences.render_cpu_interactive_explicit_sampling = false; ++ let editor = json!(h.app.render_workspace.view.raytrace); ++ assert!(image_request(&h.app).is_err(), "the original final dimensions still exceed Compact progressive admission"); ++ let wire = interactive_request(&h.app).unwrap(); ++ assert_eq!((wire["settings"]["width"].as_u64(), wire["settings"]["height"].as_u64()), (Some(3840), Some(2160))); ++ let request: ImageRequest = serde_json::from_value(json!({ ++ "integrator":"raytrace", "camera":h.app.cam, "width":3840, "height":2160, ++ "background":h.app.render_workspace.view.draft.background, "transparent_background":false, ++ "raytrace":wire["raytrace"], "cpu_progressive_every_pass":wire["cpu_progressive_every_pass"] ++ })).unwrap(); ++ let preview = cpu_request(&request).unwrap(); ++ assert_eq!((preview.width, preview.height), (1024, 576)); ++ assert!(!preview.cpu_progressive_every_pass, "the same canonical cadence flag survives derived capture"); ++ assert_eq!(preview.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); ++ assert_eq!(json!(h.app.render_workspace.view.raytrace), editor); ++ h.app.preferences.render_cpu_interactive_explicit_sampling = true; ++ let explicit = interactive_request(&h.app).unwrap(); ++ let mut explicit_request = request.clone(); ++ explicit_request.raytrace = Some(serde_json::from_value(explicit["raytrace"].clone()).unwrap()); ++ assert!(cpu_request(&explicit_request).is_err(), "31SPP exceeds the reduced image's original camera-sample envelope; never downgrade it"); ++ h.app.preferences.render_cpu_interactive_explicit_sampling = false; ++ h.app.render_workspace.view.raytrace.progressive.as_mut().unwrap().samples_per_pixel = 0; ++ assert!(interactive_request(&h.app).is_err(), "legacy preview cannot repair an invalid numerical request"); ++ assert_eq!(h.app.render_workspace.view.raytrace.progressive.unwrap().samples_per_pixel, 0); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn interactive_snapshot_policy_and_sampling_stay_captured_after_later_preference_edits() { ++ use solidcraft_engine::render::job::{CpuProgressiveOptions, Phase, interactive::VisualRevision}; ++ use std::time::Duration; ++ let mut h = interactive_ui_fixture(); ++ if !interactive_test_cpu_branch(&mut h, "interactive_snapshot_policy_and_sampling_stay_captured_after_later_preference_edits") { ++ return; ++ } ++ h.app.render_workspace.view.draft.width = 4; ++ h.app.render_workspace.view.draft.height = 4; ++ h.app.render_workspace.view.raytrace.primary_samples = 1; ++ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 741 }); ++ h.app.preferences.render_cpu_progressive_every_pass = false; ++ h.app.preferences.render_cpu_interactive_explicit_sampling = false; ++ let captured_value = interactive_request(&h.app).unwrap(); ++ let context = h.app.session.interactive_render().unwrap(); ++ context.enable(VisualRevision { scene_generation: h.app.session.revision, visual_revision: 1 }, Duration::ZERO).unwrap(); ++ let ticket = context.capture(Duration::from_millis(201)).unwrap().unwrap(); ++ let snapshot = context.snapshot(&h.app.session, ticket, &captured_value).unwrap(); ++ h.app.preferences.render_cpu_progressive_every_pass = true; ++ h.app.preferences.render_cpu_interactive_explicit_sampling = true; ++ assert_ne!(interactive_request(&h.app).unwrap(), captured_value); ++ assert!(snapshot.run().unwrap(), "the real snapshot prepares its frozen command Value"); ++ let handle = context.current().unwrap().unwrap(); ++ let status = handle.wait_timeout(Duration::from_secs(60)).unwrap(); ++ assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); ++ assert!(!status.request.cpu_progressive_every_pass); ++ assert_eq!(status.request.raytrace.as_ref().unwrap().progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 })); ++ assert_eq!(serde_json::to_value(&status.request).unwrap()["cpu_progressive_every_pass"], false, "prepared metadata keeps the canonical false value"); ++ assert!(handle.frame().unwrap().is_some()); ++ assert_eq!(h.app.render_workspace.view.raytrace.progressive, Some(CpuProgressiveOptions { samples_per_pixel: 5, seed: 741 })); ++ interactive_assert_final_export_isolation(&mut h, &handle); ++ context.disable().unwrap(); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn interactive_cadence_preference_edit_invalidates_real_capture_through_existing_request_identity() { ++ let mut h = interactive_ui_fixture(); ++ if !interactive_test_cpu_branch(&mut h, "interactive_cadence_preference_edit_invalidates_real_capture_through_existing_request_identity") { ++ return; ++ } ++ let epoch = interactive::test_clock(&h.app).as_secs_f64(); ++ h.app.run("render.interactive", json!({"action":"on"})).unwrap(); ++ interactive_clear_acceptance_frame(&mut h, epoch, true); ++ interactive_clear_acceptance_frame(&mut h, epoch + 0.201, true); ++ let held = interactive_hold_real_completed_callback(&mut h); ++ held.sender.send(held.reply).unwrap(); ++ let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.3, false, true); ++ assert!(painted); ++ output.textures_delta.clear(); ++ let old_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); ++ let old_request = interactive_request(&h.app).unwrap(); ++ h.app.preferences.render_cpu_progressive_every_pass = false; ++ interactive_control_frame(&mut h, epoch + 0.4, vec![]); ++ assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > old_visual); ++ assert!(interactive::test_current(&h.app).unwrap().is_none(), "existing edit path releases/cancels its owned capture"); ++ assert!(interactive::test_cache(&h.app).is_none()); ++ assert!(!h.app.render_workspace.interactive.pending(), "before_paint cannot launch a replacement"); ++ assert_ne!(interactive_request(&h.app).unwrap(), old_request); ++ assert!(h.app.render_workspace.view.job.is_none() && h.app.render_workspace.view.completed.is_none()); ++ // This real source completed before the edit; this test does not claim to ++ // observe cancellation of an in-flight renderer or every physical repaint. ++ assert!(held.job.frame().unwrap().is_some()); ++ h.app.run("render.interactive", json!({"action":"off"})).unwrap(); ++} +--- a/crates/ui-egui/src/render_workspace_thumbnails.rs ++++ b/crates/ui-egui/src/render_workspace_thumbnails.rs +@@ -138,6 +138,7 @@ + let permit = WorkerPermit; + let Some(setup) = app.session.doc.render.setups.get(&key.name) else { return }; + let request = solidcraft_engine::render::job::ImageRequest { ++ cpu_progressive_every_pass: true, + raster_punctual_lights: None, + raster_area_lights: None, + raster_exposure_ev: 0.0, diff --git a/proposals/render/2026-10-31/progressive-compatibility-wip/ui/source-bindings.json b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/source-bindings.json new file mode 100644 index 000000000..14f9c358c --- /dev/null +++ b/proposals/render/2026-10-31/progressive-compatibility-wip/ui/source-bindings.json @@ -0,0 +1,46 @@ +{ + "status": "SOURCE_ONLY_NOT_ADOPTED_UNCOMPILED_UNRUN", + "subpackage": "ui", + "base_source_manifest_sha256": "d38a8d946b6653864ad8918d4da662725bd24ca01b2e5aa2d3b38b47b1a7e163", + "base_rule": "Exact per-file RAW preimages only. Not current main, not a combined candidate. LF patch is review aid; RAW candidate bytes are authoritative.", + "files": [ + { + "path": "crates/render/src/job/interactive.rs", + "before_sha256": "97395da5b097d9283ac080e197f6de612b6123d9a90396e1850ca911d6ca5812", + "before_bytes": 14389, + "after_sha256": "5e0c502ffd7efdcfddc27dda0aa496d640e57eed0f775fd94a4ad036360748ab", + "after_bytes": 14435 + }, + { + "path": "crates/ui-egui/src/render_workspace.rs", + "before_sha256": "1434d0b576ab7c8a94ca7f23b9f0bb617f755509cd6f16bfafb3a86cfed05263", + "before_bytes": 111146, + "after_sha256": "cffe8870ab6a3608ef0e286009ca8caa3f5e905a4aa1c57c418dab130018d59e", + "after_bytes": 111985 + }, + { + "path": "crates/ui-egui/src/render_workspace_cpu.rs", + "before_sha256": "fd6de0f8121dc4d1bfce308c376901f65e2d920b68a756c38a25f82679db64ad", + "before_bytes": 42703, + "after_sha256": "00b1f5c25f8fe07719451683dd8d9a5f8b0b52b89f8b5e466b365cafc14e585d", + "after_bytes": 43431 + }, + { + "path": "crates/ui-egui/src/render_workspace_tests.rs", + "before_sha256": "28ddafe4a8f133c522ddf6f1e0eaaaf70f954d7b8acdb7cca44aabef9a512e47", + "before_bytes": 634699, + "after_sha256": "d9850e1996aecdcef2d3c55a5704ea7d3c29e7c237025415ce3d69a3c63f2fcf", + "after_bytes": 646092 + }, + { + "path": "crates/ui-egui/src/render_workspace_thumbnails.rs", + "before_sha256": "001729728a657f2ba0f2d1b50d1a4644f3f7ad505609cf8e674fa7f3f627e445", + "before_bytes": 7420, + "after_sha256": "85d5a8d2529df5b922243eab4f14de3b4ab684907834c4bbe29784930077e83d", + "after_bytes": 7466 + } + ], + "full_CI_native_or_readiness": false, + "candidate_whole_file_overlay_safe": false, + "shared_before_test_file_sha256": "28ddafe4a8f133c522ddf6f1e0eaaaf70f954d7b8acdb7cca44aabef9a512e47" +}