From eb848ff3c854e3bc5ec6f3739bbefbd5dec281a7 Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:55:45 +0100 Subject: [PATCH] archive: coherent C22 render source increment and exact bindings (unrun) --- proposals/render/2026-10-30/README.md | 4 + .../2026-10-31/c22-composed-source/README.md | 13 + .../c22-composed-source/c22-source.patch | 9703 +++++++++++++++++ .../c22-composed-source/source-bindings.json | 591 + 4 files changed, 10311 insertions(+) create mode 100644 proposals/render/2026-10-31/c22-composed-source/README.md create mode 100644 proposals/render/2026-10-31/c22-composed-source/c22-source.patch create mode 100644 proposals/render/2026-10-31/c22-composed-source/source-bindings.json diff --git a/proposals/render/2026-10-30/README.md b/proposals/render/2026-10-30/README.md index 9fcfd40b7..a4f534228 100644 --- a/proposals/render/2026-10-30/README.md +++ b/proposals/render/2026-10-30/README.md @@ -189,3 +189,7 @@ explicit. Source review and replay are not compilation, full CI or GPU parity. [Twelve-file source packet and limitations](../2026-10-31/cpu-directional-rgb-consumer/README.md). The complete API consumer connects captured direct visibility and RGB shading to bounded CPU image continuations, preserving legacy mode by default. Sixteen new tests are written but UNRUN. All before/candidate sources, unchanged RGB references and the exact delta are included; mixed ancestry and Raster composition requirements are explicit. This is a source archive, not an adopted complete workspace, UI feature-parity claim, test pass or production readiness result. + +## C22 composed and adopted source — uncompiled and unrun, 31 October + +[Coherent 43-path aggregate increment and source bindings](../2026-10-31/c22-composed-source/README.md). All seven reviewed units are preserved, including the original numeric oracles and two explicit neutral schema fillers. One new locale; 89 new test declarations UNRUN. A single current locked/offline metadata capture passed without source/lock changes; this is not compilation or test evidence. Staged development validation, desktop/native/GPU acceptance and full repository gates remain pending; production PR head is unchanged. diff --git a/proposals/render/2026-10-31/c22-composed-source/README.md b/proposals/render/2026-10-31/c22-composed-source/README.md new file mode 100644 index 000000000..23ae994cd --- /dev/null +++ b/proposals/render/2026-10-31/c22-composed-source/README.md @@ -0,0 +1,13 @@ +# C22 coherent source increment — 31 October + +The seven independently reviewed source units are now composed and adopted locally in 43 explicit paths, with one new locale file. This preserves the earlier C21 source elsewhere and adds 89 test declarations, all UNCOMPILED/UNRUN. One locked/offline metadata query completed and was independently audited with unchanged source, lock, Git/index/config/toolchain. Metadata is not a compiler, test or runtime result. The production PR remains draft at its earlier head. + +`c22-source.patch` is the exact aggregate source increment against the frozen C21 source identified in `source-bindings.json`, **not against bare HEAD or current main**. The bindings list every actual before/after file hash. The single genuinely new locale uses `/dev/null`; the private composition's empty-placeholder header is the only representation change. Source, hunk contents and line endings are unchanged. Do not apply this patch over an already adopted or different receiver. + +Composition order: interactive dielectric-retention test/docs alignment; CPU direct-visibility foundation; by-value visibility owner; per-light RGB shading; Raster local-light consumer; physical-glass library staging; complete directional RGB image consumer. The consumer Engine receiver already contains recovery plus Raster. Twelve overlapping paths were reconciled explicitly; only two neutral optional Raster fields were added to one new consumer fixture. Original analytic values/tolerances and other refusal assertions remain. The historical C21 failure remains preserved; the one documented test-contract alignment is not a passing rerun or producer-admission waiver. + +The source improves bounded CPU/Raster capabilities, not general feature parity. The directional flag is runtime API-only and off by default; the authored per-body transmitted-shadow UI adapter remains pending. Certified straight directional connections through thin sheets/disjoint aligned boxes do not establish arbitrary closed glass, refracted shadow connections or caustics. The library bridge stages physical recipes into the existing optical editor, preserving scalar refusal and explicit CPU consent/certification. No quality, work, memory, geometry or numeric limit was raised. + +Development validation is being prepared with one builder and existing caches: core first, the failed contract first, every eligible device-free Render LIB case and affected dependencies, then the upper build with actual Core artifact/registration equality barriers. Counts must reconcile with own compiled inventories; no test outcome is claimed. Normal full repository gates, a source-bound desktop binary, all 26 native mouse/keyboard acceptance cases and physical GPU acceptance remain pending. No whole issue item is closed by this source archive. + +Earlier individual packets and history remain in the [source index](../../2026-10-30/README.md). diff --git a/proposals/render/2026-10-31/c22-composed-source/c22-source.patch b/proposals/render/2026-10-31/c22-composed-source/c22-source.patch new file mode 100644 index 000000000..5d1ccd310 --- /dev/null +++ b/proposals/render/2026-10-31/c22-composed-source/c22-source.patch @@ -0,0 +1,9703 @@ +--- /dev/null ++++ b/assets/locales/pending/render-glass-library-route.json +@@ -0,0 +1,65 @@ ++{ ++ "en": { ++ "render.glass_library_conflict": "This body already has optical settings. Edit or remove them before preparing a different recipe.", ++ "render.glass_library_edit": "Prepare physical glass", ++ "render.glass_library_help": "Prepares the recipe in the existing editor without assigning an appearance or rendering. CPU needs explicit optical permission and a Thin sheet or Box that passes actual certification. Closed-mesh and shadow settings stay unchanged.", ++ "render.glass_library_method": "Choose CPU or GPU rendering to prepare physical glass. Raster has no physical-glass route.", ++ "render.glass_library_prepared": "Physical glass recipe prepared for editing; review its boundary and optical settings before rendering." ++ }, ++ "es": { ++ "render.glass_library_conflict": "Este cuerpo ya tiene ajustes ópticos. Edítalos o elimínalos antes de preparar otra receta.", ++ "render.glass_library_edit": "Preparar vidrio físico", ++ "render.glass_library_help": "Prepara la receta en el editor existente sin asignar un aspecto ni renderizar. CPU necesita permiso óptico explícito y una lámina o caja que supere la certificación real. No cambia los ajustes de malla cerrada ni de sombras.", ++ "render.glass_library_method": "Elige renderizado CPU o GPU para preparar vidrio físico. Raster no tiene una ruta de vidrio físico.", ++ "render.glass_library_prepared": "Receta de vidrio físico preparada para editar; revisa su frontera y sus ajustes ópticos antes de renderizar." ++ }, ++ "de": { ++ "render.glass_library_conflict": "Dieser Körper hat bereits optische Einstellungen. Bearbeite oder entferne sie, bevor du ein anderes Rezept vorbereitest.", ++ "render.glass_library_edit": "Physikalisches Glas vorbereiten", ++ "render.glass_library_help": "Bereitet das Rezept im vorhandenen Editor vor, ohne ein Aussehen zuzuweisen oder zu rendern. CPU benötigt eine ausdrückliche Freigabe der Optik und eine dünne Scheibe oder einen Quader mit tatsächlicher Zertifizierung. Einstellungen für geschlossene Netze und Schatten bleiben unverändert.", ++ "render.glass_library_method": "Wähle CPU- oder GPU-Rendering, um physikalisches Glas vorzubereiten. Raster unterstützt kein physikalisches Glas.", ++ "render.glass_library_prepared": "Glasrezept zur Bearbeitung vorbereitet; prüfe vor dem Rendern seine Begrenzung und optischen Einstellungen." ++ }, ++ "ko": { ++ "render.glass_library_conflict": "이 바디에는 이미 광학 설정이 있습니다. 다른 레시피를 준비하기 전에 기존 설정을 편집하거나 제거하세요.", ++ "render.glass_library_edit": "물리 기반 유리 준비", ++ "render.glass_library_help": "모양을 지정하거나 렌더링하지 않고 기존 편집기에서 레시피를 준비합니다. CPU에는 명시적인 광학 허용과 실제 검증을 통과하는 얇은 판 또는 상자가 필요합니다. 닫힌 메시와 그림자 설정은 변경하지 않습니다.", ++ "render.glass_library_method": "물리 기반 유리를 준비하려면 CPU 또는 GPU 렌더링을 선택하세요. Raster는 물리 기반 유리를 지원하지 않습니다.", ++ "render.glass_library_prepared": "편집할 유리 레시피를 준비했습니다. 렌더링 전에 경계와 광학 설정을 검토하세요." ++ }, ++ "ar": { ++ "render.glass_library_conflict": "لهذا الجسم إعدادات بصرية بالفعل. عدّلها أو أزلها قبل تجهيز وصفة مختلفة.", ++ "render.glass_library_edit": "تجهيز زجاج فيزيائي", ++ "render.glass_library_help": "يجهّز الوصفة في المحرر الحالي دون تعيين مظهر أو تصيير. يتطلب CPU إذنًا بصريًا صريحًا وصفيحة رقيقة أو صندوقًا يجتاز التحقق الفعلي. تبقى إعدادات الشبكة المغلقة والظلال دون تغيير.", ++ "render.glass_library_method": "اختر التصيير عبر CPU أو GPU لتجهيز زجاج فيزيائي. لا يدعم Raster الزجاج الفيزيائي.", ++ "render.glass_library_prepared": "جُهّزت وصفة الزجاج للتحرير؛ راجع حدودها وإعداداتها البصرية قبل التصيير." ++ }, ++ "he": { ++ "render.glass_library_conflict": "לגוף הזה כבר יש הגדרות אופטיות. יש לערוך או להסיר אותן לפני הכנת מתכון אחר.", ++ "render.glass_library_edit": "הכנת זכוכית פיזיקלית", ++ "render.glass_library_help": "מכין את המתכון בעורך הקיים בלי להקצות מראה או לרנדר. CPU דורש אישור אופטי מפורש ולוח דק או תיבה שעוברים אימות בפועל. הגדרות רשת סגורה וצללים אינן משתנות.", ++ "render.glass_library_method": "יש לבחור רינדור CPU או GPU כדי להכין זכוכית פיזיקלית. Raster אינו תומך בזכוכית פיזיקלית.", ++ "render.glass_library_prepared": "מתכון הזכוכית הוכן לעריכה; יש לבדוק את הגבול ואת ההגדרות האופטיות לפני הרינדור." ++ }, ++ "ja": { ++ "render.glass_library_conflict": "このボディには既に光学設定があります。別のレシピを準備する前に、既存の設定を編集または削除してください。", ++ "render.glass_library_edit": "物理ガラスを準備", ++ "render.glass_library_help": "外観の割り当てやレンダリングを行わず、既存のエディターでレシピを準備します。CPU では光学処理の明示的な許可と、実際の認証に合格する薄板またはボックスが必要です。閉じたメッシュと影の設定は変更しません。", ++ "render.glass_library_method": "物理ガラスを準備するには CPU または GPU レンダリングを選択してください。Raster は物理ガラスに対応していません。", ++ "render.glass_library_prepared": "編集用のガラスレシピを準備しました。レンダリング前に境界と光学設定を確認してください。" ++ }, ++ "vi": { ++ "render.glass_library_conflict": "Thân này đã có thiết lập quang học. Hãy sửa hoặc xóa chúng trước khi chuẩn bị công thức khác.", ++ "render.glass_library_edit": "Chuẩn bị kính vật lý", ++ "render.glass_library_help": "Chuẩn bị công thức trong trình chỉnh sửa hiện có mà không gán diện mạo hay kết xuất. CPU cần cho phép quang học rõ ràng và tấm mỏng hoặc hộp vượt qua kiểm chứng thực tế. Không đổi thiết lập lưới kín và bóng đổ.", ++ "render.glass_library_method": "Chọn kết xuất CPU hoặc GPU để chuẩn bị kính vật lý. Raster không hỗ trợ kính vật lý.", ++ "render.glass_library_prepared": "Đã chuẩn bị công thức kính để chỉnh sửa; hãy kiểm tra biên và thiết lập quang học trước khi kết xuất." ++ }, ++ "zh": { ++ "render.glass_library_conflict": "此实体已有光学设置。准备其他配方前,请编辑或移除现有设置。", ++ "render.glass_library_edit": "准备物理玻璃", ++ "render.glass_library_help": "在现有编辑器中准备配方,不分配外观,也不进行渲染。CPU 需要明确启用光学处理,并使用通过实际认证的薄片或盒体。封闭网格和阴影设置保持不变。", ++ "render.glass_library_method": "请选择 CPU 或 GPU 渲染来准备物理玻璃。Raster 不支持物理玻璃。", ++ "render.glass_library_prepared": "玻璃配方已准备好供编辑;渲染前请检查边界和光学设置。" ++ } ++} +--- a/assets/shaders/viewport.wgsl ++++ b/assets/shaders/viewport.wgsl +@@ -507,6 +507,10 @@ + var weight=1.0; + if source.w > 0.5 { + let delta=source.xyz-p; ++ // Exact coincidence has no defined source direction: no incident contribution. ++ if all(delta == vec3(0.0)) { ++ return mat2x3(vec3(0.0),vec3(0.0)); ++ } + let distance=max(length(delta),falloff.y); + direction=product_light_unit(delta); + weight=falloff.x/max(distance*distance,0.000001); +--- 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. progressive_feedback?: false; transient protected display updates during CPU progressive rendering only; true refuses raster, GPU and fixed CPU requests. Omission preserves legacy admission/submission. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.budget?: compact (legacy default), studio or workstation; see docs/render-cpu-resource-profiles.md for explicit image/geometry/memory/work limits. CPU raytrace.progressive?: {samples_per_pixel:1..profile limit, seed:u32}; requires primary_samples:1 and selected reflections.samples:1; bounded area/LED direct lights retain their existing source and emitter-sample limits; anisotropy requires fixed sampling; certified smooth thin-sheet/box dielectrics support fixed or progressive sampling under the same certificates and bounded optical transport. See docs/render-cpu-progressive.md; environment?: {path: scoped HDR, expected_sha256?: inspected digest, rotation_radians: 0, intensity: 1, samples: 16} OR {resource: saved HDR digest, rotation_radians, intensity, samples}; embedded resources cannot combine with path/hash; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS or GI. CPU runtime dielectrics support only certified thin_sheet/closed_box boundaries with explicit IOR and Beer absorption. nested_media?: false is the existing JobOptions opt-in; fixed or progressive CPU images admit only strictly nested certified closed_box boundaries with an exterior camera, while touching/partial overlaps, sheets within volumes and clearcoat combinations refuse. Other nondefault JobOptions remain unsupported on CPU; progressive/Interactive optics retain primary_samples:1 and selected reflections.samples:1 limits and never drop unsupported intent. GPU progressive uses the same nested_media field with its own certified-media contract; see docs/render-raytrace-dielectrics.md. CPU emissions are visible radiance only; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/64 for the whole strip, default16. At most8directional+8punctual+4rectangle/LED sources; shared area N. See docs/render-light-union.md. transparent_background?: false; replace?: false. With progressive:true, raytrace instead accepts GPU dielectrics/clear_coats/textures; environment instead accepts tagged hdr/embedded_hdr/sky with rotation_rad/intensity; file hdr supports expected_sha256, embedded_hdr uses a document resource digest. See docs/render-hdr-resources.md. GPU lens, studio lighting, tone_map, denoise, bounded finishing/backdrop and linear_exr retention are also available. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"), ++ .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>, ++ #[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, + nested_media: bool, + studio_weights: Option<[f64; 3]>, +@@ -114,7 +118,7 @@ + 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() { ++ 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 { +@@ -151,6 +155,8 @@ + } + } + let final_request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + camera: settings.camera, +@@ -197,6 +203,98 @@ + + #[cfg(test)] + mod union_lowering_tests { ++ ++ #[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() { +@@ -324,14 +422,41 @@ + #[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)), +- ( +- "dielectrics", +- json!([{"body_index":0,"body_name":"receiver","ior":1.5,"absorption_per_mm":[0,0,0], +- "boundary":"closed_box","thickness_mm":0}]), +- ), + ( + "anisotropic_faces", + json!([{"body_index":0,"body_name":"receiver","face":0,"tangent":[1,0,0], +@@ -342,6 +467,11 @@ + 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(); +@@ -565,6 +695,21 @@ + .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); + }; +@@ -589,7 +734,7 @@ + }; + if let Some(key) = object + .keys() +- .find(|key| !matches!(key.as_str(), "setup" | "settings" | "replace" | "studio_weights" | "progressive_feedback" | "raster_lights")) ++ .find(|key| !matches!(key.as_str(), "setup" | "settings" | "replace" | "studio_weights" | "progressive_feedback" | "raster_lights" | "raster_punctual_lights" | "raster_area_lights")) + { + return Err(bad( + command, +@@ -688,7 +833,9 @@ + } + let mut input = Start::deserialize(params).map_err(|e| bad(command, e.to_string()))?; + solidcraft_render::job::validate_raster_lights(&input.raster_lights).map_err(job_error)?; +- if input.raster_lights.is_some() ++ 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 +@@ -736,6 +883,14 @@ + } + 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 { +@@ -828,7 +983,7 @@ + } + // 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() && (settings.environment_rotation != 0.0 || settings.environment_intensity != 1.0) { ++ 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() }; +@@ -871,6 +1026,8 @@ + return Err(bad(command, "resolved executor is not installed as an image job host")); + } + let request = ImageRequest { ++ 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)?, +@@ -1102,6 +1259,8 @@ + return Err(bad(command, "image host is unavailable")); + } + let request = ImageRequest { ++ 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)?, +@@ -1299,3 +1458,48 @@ + } + 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); ++ } ++ } ++} +--- a/crates/engine/src/render_jobs.rs ++++ b/crates/engine/src/render_jobs.rs +@@ -800,6 +800,8 @@ + use solidcraft_render::job::{CpuProgressiveOptions, ImageRequest, JobOptions, RaytraceOptions}; + let (session, host) = native().unwrap(); + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + integrator: Integrator::Raytrace, +--- a/crates/gpu/src/path/denoise_tests.rs ++++ b/crates/gpu/src/path/denoise_tests.rs +@@ -157,6 +157,8 @@ + let mut camera = Camera { distance: 4.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/gpu/src/path/mod.rs ++++ b/crates/gpu/src/path/mod.rs +@@ -318,7 +318,7 @@ + } + + fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { +- if request.raster_lights.is_some() || request.raster_exposure_ev != 0.0 { ++ if request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "GPU path rendering does not accept Raster lights or Raster exposure")); + } + if request.integrator != solidcraft_render::job::Integrator::Raster || request.raytrace.is_some() { +@@ -477,7 +477,7 @@ + Ok(value) + } + fn admit(&self, scene: &ProductScene, request: &ImageRequest, options: JobOptions) -> Result { +- if request.raster_lights.is_some() || request.raster_exposure_ev != 0.0 { ++ if request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0 { + return Err(JobError::new(ErrorCode::InvalidRequest, "GPU path rendering does not accept Raster lights or Raster exposure")); + } + self.context.ensure_available()?; +--- a/crates/gpu/src/path/tests.rs ++++ b/crates/gpu/src/path/tests.rs +@@ -21,6 +21,8 @@ + let mut camera = Camera { distance: 4.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -432,6 +434,8 @@ + 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 { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/gpu/src/view.rs ++++ b/crates/gpu/src/view.rs +@@ -5456,4 +5456,62 @@ + } + eprintln!("U17_PRODUCT_SRGB supported=true formats=2 ssaa=2 materials=2 sources=2 palettes=2 exposures=3"); + } +-} ++ ++ /// In this existing orthographic fixture, pixel(32,32) is exactly ++ /// (5/32,-5/32,0): clip edges are +/-1/2 at integer screen16 and48. ++ /// The source shares that representable point. No epsilon weakens delta0. ++ #[cfg(not(target_arch = "wasm32"))] ++ #[test] ++ fn raster_local_model_exact_coincidence_is_black_then_positive_source_repaints_both_formats() { ++ let (_,device,queue) = match crate::open_headless() { ++ Ok(device) => device, ++ Err(error) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => { ++ eprintln!("RASTER_LOCAL_MODEL_ZERO supported=false reason={error}"); ++ return; ++ } ++ Err(error) => panic!("required GPU adapter unavailable: {error}"), ++ }; ++ for format in [wgpu::TextureFormat::Rgba8Unorm,wgpu::TextureFormat::Rgba8UnormSrgb] { ++ for pbr in [false,true] { ++ let mut scene = GpuScene::default(); ++ let rgb = [94,128,160]; ++ let colour = scene.color([rgb[0],rgb[1],rgb[2],255]); ++ let linear = rgb.map(solidcraft_geom::srgb::decode8); ++ let surface = solidcraft_render::surface::OpaqueSurface::new(solidcraft_geom::Vec3::new(linear[0],linear[1],linear[2]),0.0,1.0,1.0).unwrap(); ++ for p in [[-5.0,-5.0,0.0],[5.0,-5.0,0.0],[5.0,5.0,0.0],[-5.0,-5.0,0.0],[5.0,5.0,0.0],[-5.0,5.0,0.0]] { ++ if pbr { scene.pbr_tri(p,[0.0,0.0,1.0],surface); } ++ else { scene.tri(p,[0.0,0.0,1.0],colour); } ++ } ++ let depth = crate::depth_format(&device,true); ++ let mut renderer = Renderer::new(&device,GpuTarget {format,depth:Some(depth),samples:1,tess:false,oit:false},None); ++ let mut frame = test_frame(scene,1.0); ++ let design = render_frame_format(&mut renderer,&device,&queue,&frame,true,format); ++ frame.product = true; ++ let at = (32*64+32)*4; ++ for kind in [1.0,2.0,3.0] { ++ let pi = std::f32::consts::PI; ++ let source = [0.15625,-0.15625,0.0,kind,pi,pi,pi,0.8,0.0,0.0,-1.0,1.0,1.0,0.001,0.0,0.0]; ++ frame.product_lights = Some(vec![source]); ++ let zero = render_frame_format(&mut renderer,&device,&queue,&frame,true,format); ++ assert_eq!(zero.len(),64*64*4); ++ assert_eq!(&zero[at..at+4],&[0,0,0,255],"{format:?} pbr={pbr} kind={kind}"); ++ frame.product_lights.as_mut().unwrap()[0][2]=1.0; ++ let positive = render_frame_format(&mut renderer,&device,&queue,&frame,true,format); ++ // Unit distance/cosines, reference^2 or projected area1: ++ // source PI cancels Lambert /PI for every source family. ++ for channel in 0..3 { ++ let radiance = linear[channel]*f64::from(pi)/std::f64::consts::PI; ++ let expected = solidcraft_geom::srgb::encode8(radiance/(1.0+radiance)); ++ assert!(positive[at+channel].abs_diff(expected)<=1,"{format:?} pbr={pbr} kind={kind} channel={channel}: {} != {expected}",positive[at+channel]); ++ } ++ assert_eq!(positive[at+3],255); ++ assert_eq!(&positive[..4],&[255;4]); ++ } ++ frame.product=false; ++ frame.product_lights=None; ++ assert_eq!(render_frame_format(&mut renderer,&device,&queue,&frame,true,format),design,"legacy Design restored exactly"); ++ } ++ } ++ eprintln!("RASTER_LOCAL_MODEL_ZERO supported=true formats=2 materials=2 sources=3"); ++ } ++} +--- a/crates/render/examples/cpu_resource_smoke.rs ++++ b/crates/render/examples/cpu_resource_smoke.rs +@@ -31,6 +31,8 @@ + let mut camera = Camera { distance: 65.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/job/host.rs ++++ b/crates/render/src/job/host.rs +@@ -188,6 +188,8 @@ + 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, +@@ -260,6 +262,72 @@ + 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); + } + } + +@@ -1323,6 +1391,9 @@ + 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(); +@@ -1352,7 +1423,7 @@ + partial: Option, + ) -> Result { + request.validate_raster_request()?; +- if self.0.executor.is_some() && (request.raster_lights.is_some() || request.raster_exposure_ev != 0.0) { ++ 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 { +@@ -1791,6 +1862,8 @@ + ) + .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, +@@ -2019,6 +2092,8 @@ + 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, +@@ -2091,6 +2166,8 @@ + 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, +@@ -2206,6 +2283,8 @@ + + fn request() -> ImageRequest { + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/job/host_regrade_tests.rs ++++ b/crates/render/src/job/host_regrade_tests.rs +@@ -47,6 +47,8 @@ + let begins = Arc::new(AtomicUsize::new(0)); + let host = ImageHost::cooperative_with(Arc::new(FixtureExecutor(begins.clone()))); + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/job/host_tests.rs ++++ b/crates/render/src/job/host_tests.rs +@@ -655,6 +655,8 @@ + + fn request() -> ImageRequest { + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -2132,3 +2134,75 @@ + 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); ++ } ++} +--- a/crates/render/src/job/image.rs ++++ b/crates/render/src/job/image.rs +@@ -108,7 +108,7 @@ + /// pixel/codec allowance, then let the ray tracer charge its actual BVH and film. + #[cfg(feature = "raytrace-cpu")] + pub(crate) fn admit_raytrace_source(scene: &ProductScene, request: &ImageRequest, budget: super::CpuBudget) -> Result { +- if request.raster_lights.is_some() || request.raster_exposure_ev != 0.0 { ++ if request.has_explicit_raster_lights() || request.raster_exposure_ev != 0.0 { + return Err(invalid("Raster-only lighting and exposure cannot enter CPU ray tracing")); + } + budget.validate_execution()?; +@@ -167,7 +167,7 @@ + image_limits: crate::RenderLimits, + ) -> Result { + request.validate_raster_request()?; +- if request.raster_lights.is_some() && scene.has_transmission() { ++ if request.has_explicit_raster_lights() && scene.has_transmission() { + return Err(invalid("explicit Raster lights do not implement physical transmission")); + } + if !request.camera.is_valid() { +@@ -356,7 +356,10 @@ + sort_dst: usize, + pixels: Vec<[u8; 4]>, + depth: Vec, ++ // Weighted projected light work for the existing work ceiling. + pixel_tests: u64, ++ // Unweighted bounding-box pixel visits, matching pixel_done Running units. ++ pixel_progress_tests: u64, + pixel_done: u64, + draw: usize, + triangle: Option, +@@ -409,6 +412,7 @@ + pixels, + depth, + pixel_tests: 0, ++ pixel_progress_tests: 0, + pixel_done: 0, + draw: 0, + triangle: None, +@@ -427,7 +431,7 @@ + Stage::Clear | Stage::Opaque | Stage::Glass | Stage::Downsample => Progress { + phase: Phase::Running, + done: self.pixel_done, +- total: self.pixel_tests + (self.sw * self.sh) as u64 + u64::from(self.request.width) * u64::from(self.request.height), ++ total: self.pixel_progress_tests + (self.sw * self.sh) as u64 + u64::from(self.request.width) * u64::from(self.request.height), + }, + Stage::Encode => Progress { + phase: Phase::Encoding, +@@ -583,10 +587,12 @@ + if let Some(triangle) = self.project(draw)? { + let [x0, x1, y0, y1] = triangle.bounds; + let tests = ((x1 - x0 + 1) as u64).checked_mul((y1 - y0 + 1) as u64).ok_or_else(|| limit("pixel work overflow"))?; +- self.pixel_tests = self.pixel_tests.checked_add(tests).ok_or_else(|| limit("pixel work overflow"))?; ++ let weighted_tests = tests.checked_mul(self.request.raster_light_work_factor()?).ok_or_else(|| limit("pixel work overflow"))?; ++ self.pixel_tests = self.pixel_tests.checked_add(weighted_tests).ok_or_else(|| limit("pixel work overflow"))?; + if self.pixel_tests > MAX_PIXEL_TESTS { + return Err(limit("projected product exceeds 128000000 pixel tests")); + } ++ self.pixel_progress_tests = self.pixel_progress_tests.checked_add(tests).ok_or_else(|| limit("pixel progress overflow"))?; + draw.depth = triangle.centre_depth; + if triangle.opacity >= 1.0 { + self.opaque.push(draw); +@@ -679,9 +685,7 @@ + self.sw, + self.back, + eye, +- self.request.studio_weights, +- self.request.raster_lights.as_deref(), +- self.request.raster_exposure_ev, ++ &self.request, + &mut self.pixels, + &mut self.depth, + )?; +@@ -743,18 +747,18 @@ + } + } + +-#[allow(clippy::too_many_arguments)] + fn raster_pixel( + t: &Triangle, + width: usize, + back: Vec3, + eye: Option, +- studio_weights: Option<[f64; 3]>, +- raster_lights: Option<&[super::DirectionalLightOptions]>, +- raster_exposure_ev: f64, ++ request: &ImageRequest, + pixels: &mut [[u8; 4]], + depth: &mut [f32], + ) -> Result<()> { ++ let studio_weights = request.studio_weights; ++ let raster_lights = request.raster_lights.as_deref(); ++ let raster_exposure_ev = request.raster_exposure_ev; + let [a, b, c] = t.points; + let (x, y) = (t.x as f64 + 0.5, t.y as f64 + 0.5); + let w0 = ((b[0] - x) * (c[1] - y) - (b[1] - y) * (c[0] - x)) / t.area; +@@ -787,7 +791,8 @@ + return Ok(()); + } + let n = t.normals.iter().zip(weights).fold(Vec3::ZERO, |v, (n, w)| v + *n * (w / sum)).normalized().unwrap_or(Vec3::Z); +- let colour = if let Some(lights) = raster_lights { ++ let colour = if request.has_explicit_raster_lights() { ++ let lights = raster_lights.unwrap_or(&[]); + let surface = if let Some(surface) = t.surface { + surface + } else { +@@ -796,7 +801,14 @@ + }; + let world = t.world.iter().zip(weights).fold(Vec3::ZERO, |p, (v, w)| p + *v * (w / sum)); + let view = eye.map_or(back, |eye| eye - world); +- let radiance = crate::studio::shade_directional(surface, n, view, lights).map_err(|e| invalid(&e.to_string()))?; ++ let radiance = if request.has_local_raster_lights() { ++ crate::studio::shade_schematic( ++ surface, n, view, world, lights, request.raster_punctual_lights.as_deref().unwrap_or(&[]), ++ request.raster_area_lights.as_deref().unwrap_or(&[]), ++ ) ++ } else { ++ crate::studio::shade_directional(surface, n, view, lights) ++ }.map_err(|e| invalid(&e.to_string()))?; + let mapped = crate::studio::tone_map(expose_raster(radiance, raster_exposure_ev)?).map_err(|e| invalid(&e.to_string()))?; + [mapped.x, mapped.y, mapped.z] + } else if let Some(surface) = t.surface { +--- a/crates/render/src/job/image_tests.rs ++++ b/crates/render/src/job/image_tests.rs +@@ -98,6 +98,8 @@ + let mut camera = Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Front); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -596,3 +598,218 @@ + } + } + } ++ ++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)); ++ } ++} +--- a/crates/render/src/job/led_strip/tests.rs ++++ b/crates/render/src/job/led_strip/tests.rs +@@ -192,6 +192,8 @@ + let mut camera = Camera { distance: 50.0, ..Default::default() }; + camera.set_view(StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/job/mod.rs ++++ b/crates/render/src/job/mod.rs +@@ -52,7 +52,11 @@ + 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, validate as validate_raster_lights}; ++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. +@@ -429,6 +433,38 @@ + 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")] +@@ -687,6 +723,8 @@ + 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")] +@@ -723,6 +761,7 @@ + fn default() -> Self { + Self { + dielectric_transport: CpuDielectricTransport::LegacyBounded, ++ directional_shadow_transmission: false, + budget: CpuBudget::Compact, + progressive: None, + punctual_lights: None, +@@ -744,6 +783,10 @@ + } + } + ++fn directional_shadow_disabled(value: &bool) -> bool { ++ !*value ++} ++ + fn single_primary_sample(samples: &u8) -> bool { + *samples == 1 + } +@@ -781,6 +824,12 @@ + 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); + } +@@ -988,31 +1037,7 @@ + } + if let Some(lights) = &self.area_lights { + for light in lights { +- use solidcraft_geom::Vec3; +- let vec = |v: [f64; 3]| Vec3::new(v[0], v[1], v[2]); +- let c = vec(light.center_mm); +- let u = vec(light.edge_u_mm); +- let v = vec(light.edge_v_mm); +- if !c.is_finite() +- || !u.is_finite() +- || !v.is_finite() +- || !light.color.iter().all(|x| x.is_finite() && (0.0..=1.0).contains(x)) +- || !light.intensity.is_finite() +- || !(0.0..=64.0).contains(&light.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")); +- } +- } +- } ++ light.validate()?; + } + } + if let Some(lights) = &self.punctual_lights { +@@ -1069,6 +1094,14 @@ + 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(()) + } +@@ -1084,6 +1117,11 @@ + /// 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]>, +@@ -1116,6 +1154,28 @@ + } + + 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) { +@@ -1127,7 +1187,9 @@ + return Err(JobError::new(ErrorCode::InvalidRequest, "Raster exposure cannot enter another integrator or captured GPU resources")); + } + raster_lights::validate(&self.raster_lights)?; +- if self.raster_lights.is_some() ++ 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() +@@ -1143,23 +1205,29 @@ + } + + pub fn raster_lights_retained_bytes(&self) -> Result { +- raster_lights::retained_bytes(&self.raster_lights) ++ 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) ++ 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.raster_lights.is_none() { ++ if !self.has_explicit_raster_lights() { + return Ok(self.clone()); + } + Ok(Self { + 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(), +@@ -1211,6 +1279,133 @@ + } + #[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() { +--- a/crates/render/src/job/png.rs ++++ b/crates/render/src/job/png.rs +@@ -104,6 +104,8 @@ + + fn request(width: u32, height: u32) -> ImageRequest { + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + width, +--- a/crates/render/src/job/raster_lights.rs ++++ b/crates/render/src/job/raster_lights.rs +@@ -122,3 +122,96 @@ + } + deserializer.deserialize_option(Nullable) + } ++ ++/// New local families share the real DTO validators with CPU transport. ++pub fn validate_punctual(lights: &Option>) -> Result<()> { ++ if let Some(lights) = lights { ++ if lights.len() > 8 || lights.capacity() > 8 { ++ return Err(invalid("Raster point/spot length and capacity must be at most eight")); ++ } ++ for light in lights { ++ light.validate()?; ++ } ++ } ++ Ok(()) ++} ++ ++pub fn validate_areas(lights: &Option>) -> Result<()> { ++ if let Some(lights) = lights { ++ if lights.len() > 4 || lights.capacity() > 4 { ++ return Err(invalid("Raster rectangular length and capacity must be at most four")); ++ } ++ for light in lights { ++ light.validate()?; ++ } ++ } ++ Ok(()) ++} ++ ++pub fn deserialize_punctual<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { ++ let lights = super::punctual::bounded_punctual(deserializer)?; ++ validate_punctual(&lights).map_err(serde::de::Error::custom)?; ++ Ok(lights) ++} ++ ++pub fn deserialize_areas<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result>, D::Error> { ++ let lights = super::bounded_area_lights(deserializer)?; ++ validate_areas(&lights).map_err(serde::de::Error::custom)?; ++ Ok(lights) ++} ++ ++pub(super) fn try_copy_punctual(lights: &Option>) -> Result>> { ++ validate_punctual(lights)?; ++ let Some(source) = lights else { return Ok(None) }; ++ if source.is_empty() { ++ return Ok(Some(Vec::new())); ++ } ++ let mut copy = Vec::new(); ++ copy.try_reserve_exact(8).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve Raster point/spot lights"))?; ++ if copy.capacity() > 8 { ++ return Err(invalid("Raster point/spot allocation exceeded its bounded capacity")); ++ } ++ // Fixed-size DTO: the admitted reserve covers every push, without hidden allocation. ++ copy.extend(source.iter().copied()); ++ Ok(Some(copy)) ++} ++ ++pub(super) fn try_copy_areas(lights: &Option>) -> Result>> { ++ validate_areas(lights)?; ++ let Some(source) = lights else { return Ok(None) }; ++ if source.is_empty() { ++ return Ok(Some(Vec::new())); ++ } ++ let mut copy = Vec::new(); ++ copy.try_reserve_exact(4).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve Raster rectangular lights"))?; ++ if copy.capacity() > 4 { ++ return Err(invalid("Raster rectangular allocation exceeded its bounded capacity")); ++ } ++ // RectangleLightOptions contains only fixed arrays and a scalar. ++ copy.extend(source.iter().cloned()); ++ Ok(Some(copy)) ++} ++ ++pub(super) fn local_retained_bytes(punctual: &Option>, areas: &Option>) -> Result { ++ validate_punctual(punctual)?; ++ validate_areas(areas)?; ++ let p = punctual.as_ref().map_or(0, Vec::capacity); ++ let a = areas.as_ref().map_or(0, Vec::capacity); ++ p.checked_mul(std::mem::size_of::()) ++ .and_then(|n| a.checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m))) ++ .and_then(|n| u64::try_from(n).ok()) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster local retained size overflow")) ++} ++ ++pub(super) fn local_task_bytes(punctual: &Option>, areas: &Option>) -> Result { ++ validate_punctual(punctual)?; ++ validate_areas(areas)?; ++ // Covers the original public-task Vec capacity even for Some(empty), and ++ // the bounded fallible host-copy capacity. No allocation occurs here on valid input. ++ let p = if punctual.is_some() { 8usize } else { 0 }; ++ let a = if areas.is_some() { 4usize } else { 0 }; ++ p.checked_mul(std::mem::size_of::()) ++ .and_then(|n| a.checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m))) ++ .and_then(|n| u64::try_from(n).ok()) ++ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Raster local task size overflow")) ++} +--- a/crates/render/src/job/regrade.rs ++++ b/crates/render/src/job/regrade.rs +@@ -94,6 +94,8 @@ + return self.pending(done, total); + } + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -178,6 +180,8 @@ + } + self.linear = None; + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/job/rt2_tests.rs ++++ b/crates/render/src/job/rt2_tests.rs +@@ -6,6 +6,8 @@ + + fn request(integrator: Integrator) -> ImageRequest { + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -178,3 +180,67 @@ + 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(); ++} +--- a/crates/render/src/raytrace/anisotropic_faces_tests.rs ++++ b/crates/render/src/raytrace/anisotropic_faces_tests.rs +@@ -146,6 +146,8 @@ + fn decoded_cpu_png_rotates_only_the_two_explicit_planar_targets() { + fn render(scene: ProductScene, camera: Camera, options: RaytraceOptions) -> ::image::RgbaImage { + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs ++++ b/crates/render/src/raytrace/anisotropic_reflection_image_tests.rs +@@ -64,6 +64,8 @@ + ..Default::default() + }; + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/raytrace/deterministic_primary_tests.rs ++++ b/crates/render/src/raytrace/deterministic_primary_tests.rs +@@ -64,6 +64,8 @@ + ..Default::default() + }; + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -206,9 +208,9 @@ + 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.options, legacy.options); ++ 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.options.reflections.as_ref().unwrap().samples, 64); ++ 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); +@@ -231,6 +233,8 @@ + ..Default::default() + }; + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -354,7 +358,7 @@ + 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 mut options = previous.options; ++ 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 }] +@@ -407,7 +411,7 @@ + if options.area_lights.is_some() { + options.seed = Some(seed); + } +- let mut scene = previous.scene; ++ let mut scene = fixture_scene; + if partial { + let mesh = Arc::get_mut(&mut scene.meshes[0].mesh).unwrap(); + mesh.positions[0].x = 0.0; +@@ -514,12 +518,16 @@ + 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 => task.options.reflections.as_mut().unwrap().bodies[0].body = "Visible".into(), ++ 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.options.primary_samples, ++ 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, +@@ -584,7 +592,7 @@ + + 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 mut options = previous.options; ++ 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(), +@@ -596,7 +604,7 @@ + options.reflections.as_mut().unwrap().bodies[0].body = "Visible".into(); + } + let request = ImageRequest { raytrace: Some(options.clone()), ..previous.request }; +- ImageTask::new_with_environment(previous.scene, request, previous.cancel, options, Some(environment())).unwrap() ++ ImageTask::new_with_environment(fixture_scene, request, previous.cancel, options, Some(environment())).unwrap() + } + + #[test] +--- a/crates/render/src/raytrace/dielectric.rs ++++ b/crates/render/src/raytrace/dielectric.rs +@@ -386,6 +386,318 @@ + Ok(ExactBoxFace { point, axis, outward, entering: direction * outward < 0.0 }) + } + ++/// Hard crossing ceiling for eight disjoint certified boxes (two faces each). ++pub const MAX_DIRECT_CROSSINGS: u8 = (MAX_OVERRIDES * 2) as u8; ++ ++#[derive(Clone, Copy)] ++struct DirectHit { ++ body: usize, ++ vertices: [Vec3; 3], ++ geometry: super::TriangleHit, ++} ++ ++/// Incremental RGB visibility along ONE straight exterior-to-exterior connection. ++/// This is a direct-light approximation, not refracted transport or caustics. ++/// Selected optics are revalidated and certified against the borrowed capture. ++/// Boxes must be disjoint; sheets touching/inside boxes and endpoints on/inside ++/// boxes refuse. Unselected geometry blocks. The interval is [min,max): geometry ++/// exactly at a finite light endpoint does not block that light. ++/// ++/// No BVH tie API exists for this consumer yet. A pass scans the captured source, ++/// one triangle (or body transition) per step. Equal-depth different bodies refuse ++/// rather than silently skipping an opaque blocker behind a selected boundary. ++/// Cost is O((crossings+1)*(triangles+bodies)), not accelerated traversal. Every ++/// step debits the caller's cumulative work and checks cancellation. Memory is ++/// fixed, with borrowed scene/options. Valid setup/steps create no containers; ++/// invalid options may construct the existing validator's bounded error String. ++/// The future prepared-scene consumer passes its existing `PreparedScene.source`. ++pub struct DirectVisibility<'a> { ++ source: &'a ProductScene, ++ options: &'a crate::job::RaytraceOptions, ++ state: DirectVisibilityState, ++} ++ ++// Entirely private, reference-free and deliberately neither Clone nor Copy. ++struct DirectVisibilityState { ++ certificates: [Option; MAX_OVERRIDES], ++ ray: super::Ray, ++ body: usize, ++ triangle: usize, ++ scanned: usize, ++ nearest: Option, ++ ambiguous: bool, ++ optical: bool, ++ medium: Option<(usize, Vec3)>, ++ sheets: u8, ++ transmittance: Vec3, ++ crossings: u8, ++ crossing_limit: u8, ++ terminal: bool, ++} ++ ++impl<'a> DirectVisibility<'a> { ++ /// Bounded setup: at most eight small certificates and 64 overlap checks. ++ /// Setup also spends the SAME caller-owned budget; no fresh work credit. ++ pub fn new( ++ source: &'a ProductScene, ++ options: &'a crate::job::RaytraceOptions, ++ ray: super::Ray, ++ crossing_limit: u8, ++ work: &mut super::WorkBudget, ++ cancel: &crate::job::CancelToken, ++ ) -> Result { ++ work.tick(cancel)?; ++ if !(1..=MAX_DIRECT_CROSSINGS).contains(&crossing_limit) || source.meshes.len() > crate::job::MAX_CPU_BODIES { ++ return Err(TraceError::InvalidInput("direct visibility crossing or body bound")); ++ } ++ options.validate().map_err(|_| TraceError::InvalidInput("invalid direct visibility options"))?; ++ let mut certificates = [None; MAX_OVERRIDES]; ++ let start = ray.at(ray.interval()[0])?; ++ let end = ray.at(ray.interval()[1])?; ++ for (slot, input) in certificates.iter_mut().zip(&options.dielectrics) { ++ work.tick(cancel)?; ++ let certificate = certify(source, input)?; ++ if let Certificate::ClosedBox(bounds) = certificate { ++ if contains(bounds, ray.origin()) || contains(bounds, start) || contains(bounds, end) { ++ return Err(TraceError::InvalidInput("direct visibility endpoints must be outside certified boxes")); ++ } ++ } ++ *slot = Some(certificate); ++ } ++ for (i, a) in certificates.iter().take(options.dielectrics.len()).enumerate() { ++ for (j, b) in certificates.iter().take(options.dielectrics.len()).enumerate().skip(i + 1) { ++ work.tick(cancel)?; ++ let (Some(a), Some(b)) = (a, b) else { continue }; ++ let bounds = |slot: usize, certificate: Certificate| -> Result { ++ match certificate { ++ Certificate::ClosedBox(bounds) => Ok(bounds), ++ Certificate::ThinSheet => { ++ let input = options.dielectrics.get(slot).ok_or(TraceError::Internal("direct certificate slot"))?; ++ let body = source.meshes.get(input.body_index).ok_or(TraceError::Internal("direct certificate body"))?; ++ let bounds = body.mesh.bounds(); ++ Bounds::new(bounds.min, bounds.max) ++ } ++ } ++ }; ++ if (matches!(a, Certificate::ClosedBox(_)) || matches!(b, Certificate::ClosedBox(_))) ++ && overlaps(bounds(i, *a)?, bounds(j, *b)?) ++ { ++ return Err(TraceError::InvalidInput("direct visibility boxes must be disjoint from other selected boundaries")); ++ } ++ } ++ } ++ super::check_cancel(cancel)?; ++ Ok(Self { ++ source, options, state: DirectVisibilityState { ++ certificates, ray, body: 0, triangle: 0, scanned: 0, ++ nearest: None, ambiguous: false, optical: false, medium: None, sheets: 0, ++ transmittance: Vec3::new(1.0, 1.0, 1.0), crossings: 0, crossing_limit, terminal: false, ++ }, ++ }) ++ } ++ ++ /// None means real work remains. Only Some(rgb) is a completed connection. ++ /// Work/crossing exhaustion, cancellation and ambiguity are errors, never black ++ /// or white fallback values. Success OR error makes this cursor terminal. ++ pub fn step(&mut self, work: &mut super::WorkBudget, cancel: &crate::job::CancelToken) -> Result> { ++ if self.state.terminal { ++ return Err(TraceError::InvalidInput("direct visibility cursor is terminal")); ++ } ++ let result = self.advance(work, cancel); ++ if !matches!(result, Ok(None)) { ++ self.state.terminal = true; ++ } ++ result ++ } ++ ++ fn advance(&mut self, work: &mut super::WorkBudget, cancel: &crate::job::CancelToken) -> Result> { ++ work.tick(cancel)?; ++ if !self.state.optical { ++ if let Some(body) = self.source.meshes.get(self.state.body) { ++ // A certified sheet is ONE plane. Its two triangles can round ++ // their depths differently at a shared edge; it must never be ++ // attenuated twice. Skip that entire immutable certified body ++ // after its first crossing, not a numerical distance interval. ++ if self.options.dielectrics.iter().enumerate().any(|(slot, input)| input.body_index == self.state.body && self.state.sheets & (1u8 << slot) != 0) { ++ self.state.body += 1; ++ self.state.triangle = 0; ++ return Ok(None); ++ } ++ if let Some(indices) = body.mesh.triangles.get(self.state.triangle) { ++ self.state.scanned = self.state.scanned.checked_add(1).filter(|n| *n <= crate::job::MAX_CPU_TRIANGLES) ++ .ok_or(TraceError::WorkLimit)?; ++ let mut vertices = [Vec3::ZERO; 3]; ++ for (point, index) in vertices.iter_mut().zip(indices) { ++ *point = *body.mesh.positions.get(*index as usize).ok_or(TraceError::InvalidInput("direct visibility vertex index"))?; ++ } ++ self.state.triangle += 1; ++ if let Some(geometry) = Triangle::new(vertices)?.intersect(&self.state.ray) { ++ if geometry.distance < self.state.ray.interval()[1] { ++ let hit = DirectHit { body: self.state.body, vertices, geometry }; ++ match self.state.nearest { ++ None => self.state.nearest = Some(hit), ++ Some(old) if geometry.distance < old.geometry.distance => { ++ self.state.nearest = Some(hit); ++ self.state.ambiguous = false; ++ } ++ Some(old) if geometry.distance == old.geometry.distance && old.body != self.state.body => self.state.ambiguous = true, ++ _ => {} ++ } ++ } ++ } ++ } else { ++ self.state.body += 1; ++ self.state.triangle = 0; ++ } ++ return Ok(None); ++ } ++ self.state.optical = true; ++ return Ok(None); ++ } ++ if self.state.ambiguous { ++ return Err(TraceError::InvalidInput("coincident direct visibility bodies are ambiguous")); ++ } ++ let Some(hit) = self.state.nearest else { ++ return if self.state.medium.is_some() { ++ Err(TraceError::InvalidInput("direct visibility missed its certified box exit")) ++ } else { ++ Ok(Some(self.state.transmittance)) ++ }; ++ }; ++ let Some((slot, input)) = self.options.dielectrics.iter().enumerate().find(|(_, input)| input.body_index == hit.body) else { ++ return Ok(Some(Vec3::ZERO)); ++ }; ++ if self.state.crossings == self.state.crossing_limit { ++ return Err(TraceError::WorkLimit); ++ } ++ let outward = hit.geometry.geometric_normal; ++ let entering = outward.dot(self.state.ray.direction()) < 0.0; ++ let normal = if entering { outward } else { -outward }; ++ match self.state.certificates.get(slot).copied().flatten().ok_or(TraceError::Internal("direct visibility certificate missing"))? { ++ Certificate::ThinSheet => { ++ if self.state.medium.is_some() { ++ return Err(TraceError::InvalidInput("direct visibility sheet inside a box")); ++ } ++ let (_, _, transmission) = thin_sheet(self.state.ray.direction(), normal, input)?; ++ self.state.transmittance = multiply(self.state.transmittance, transmission); ++ self.state.sheets |= 1u8 << slot; ++ } ++ Certificate::ClosedBox(bounds) => { ++ let [a, b, c] = hit.vertices; ++ let [wa, wb, wc] = hit.geometry.barycentric; ++ let face = exact_box_face(bounds, hit.vertices, outward, a * wa + b * wb + c * wc, self.state.ray)?; ++ // External-angle Fresnel on BOTH straight connections. The ray is ++ // not bent, so an internal critical angle here would invent TIR. ++ let transmit = 1.0 - interface(self.state.ray.direction(), normal, 1.0, input.ior)?.reflectance; ++ self.state.transmittance = self.state.transmittance * transmit; ++ if entering { ++ if self.state.medium.is_some() { ++ return Err(TraceError::InvalidInput("direct visibility entered overlapping boxes")); ++ } ++ self.state.medium = Some((slot, face.point)); ++ } else { ++ let (active, start) = self.state.medium.ok_or(TraceError::InvalidInput("direct visibility exited without entry"))?; ++ if active != slot { ++ return Err(TraceError::InvalidInput("direct visibility box exit identity mismatch")); ++ } ++ let delta = face.point - start; ++ let scale = delta.x.abs().max(delta.y.abs()).max(delta.z.abs()); ++ if scale == 0.0 || !scale.is_finite() { ++ return Err(TraceError::InvalidInput("direct visibility box segment is degenerate")); ++ } ++ let distance = scale * (delta / scale).len2().sqrt(); ++ self.state.transmittance = multiply(self.state.transmittance, attenuation(input.absorption_per_mm, distance)?); ++ self.state.medium = None; ++ } ++ } ++ } ++ if !self.state.transmittance.is_finite() || [self.state.transmittance.x, self.state.transmittance.y, self.state.transmittance.z].into_iter().any(|v| !(0.0..=1.0).contains(&v)) { ++ return Err(TraceError::InvalidInput("invalid direct visibility transmittance")); ++ } ++ self.state.crossings += 1; ++ if self.state.transmittance == Vec3::ZERO { ++ return Ok(Some(Vec3::ZERO)); ++ } ++ // Preserve the original origin AND normalized direction. Calling Ray::new ++ // again could renormalize it and change the tie/interval calculations. ++ self.state.ray.min = hit.geometry.distance.next_up(); ++ if self.state.ray.min >= self.state.ray.max { ++ return if self.state.medium.is_some() { ++ Err(TraceError::InvalidInput("direct visibility interval cannot resolve the exit")) ++ } else { ++ Ok(Some(self.state.transmittance)) ++ }; ++ } ++ self.state.body = 0; ++ self.state.triangle = 0; ++ self.state.scanned = 0; ++ self.state.nearest = None; ++ self.state.ambiguous = false; ++ self.state.optical = false; ++ Ok(None) ++ } ++} ++ ++/// Owns one immutable capture and at most one direct-light connection inline. ++/// Moving this owner moves its scene/options and reference-free cursor together. ++/// No state or mutable capture access escapes: certificates cannot be rebound to ++/// a different scene/options pair by a sibling consumer. Construction only moves ++/// the capture; `begin` retains the original validation and caller-owned ledger. ++/// The existing borrowed `DirectVisibility` API remains independently available. ++pub(super) struct DirectVisibilityOwner { ++ source: ProductScene, ++ options: crate::job::RaytraceOptions, ++ state: Option, ++} ++ ++impl DirectVisibilityOwner { ++ pub(super) fn new(source: ProductScene, options: crate::job::RaytraceOptions) -> Self { ++ Self { source, options, state: None } ++ } ++ ++ /// Test fixtures may consume their capture; no cursor state survives or escapes. ++ #[cfg(test)] ++ pub(super) fn into_capture(self) -> (ProductScene, crate::job::RaytraceOptions) { ++ (self.source, self.options) ++ } ++ ++ pub(super) fn source(&self) -> &ProductScene { ++ &self.source ++ } ++ ++ pub(super) fn options(&self) -> &crate::job::RaytraceOptions { ++ &self.options ++ } ++ ++ /// Start explicitly on this owner's capture. Never replace an active scan. ++ /// A failed constructor preserves the previous idle or terminal state. ++ pub(super) fn begin( ++ &mut self, ++ ray: super::Ray, ++ crossing_limit: u8, ++ work: &mut super::WorkBudget, ++ cancel: &crate::job::CancelToken, ++ ) -> Result<()> { ++ if self.state.as_ref().is_some_and(|state| !state.terminal) { ++ return Err(TraceError::InvalidInput("direct visibility connection is active")); ++ } ++ let state = DirectVisibility::new(&self.source, &self.options, ray, crossing_limit, work, cancel)?.state; ++ self.state = Some(state); ++ Ok(()) ++ } ++ ++ /// Advance once, rebinding only to the immutable capture owned here. ++ /// Retain terminal state on success AND error; only explicit `begin` starts ++ /// another connection. Rebinding itself has no work, validation or allocation. ++ pub(super) fn step(&mut self, work: &mut super::WorkBudget, cancel: &crate::job::CancelToken) -> Result> { ++ let state = self.state.take().ok_or(TraceError::InvalidInput("direct visibility connection has not begun"))?; ++ let mut cursor = DirectVisibility { source: &self.source, options: &self.options, state }; ++ let result = cursor.step(work, cancel); ++ self.state = Some(cursor.state); ++ result ++ } ++} ++ + #[cfg(test)] + #[path = "dielectric_tests.rs"] + pub(super) mod tests; +--- a/crates/render/src/raytrace/dielectric_tests.rs ++++ b/crates/render/src/raytrace/dielectric_tests.rs +@@ -43,6 +43,8 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -735,3 +737,453 @@ + 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"); ++} +--- a/crates/render/src/raytrace/environment_image_tests.rs ++++ b/crates/render/src/raytrace/environment_image_tests.rs +@@ -35,6 +35,8 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/raytrace/environment_reflection_tests.rs ++++ b/crates/render/src/raytrace/environment_reflection_tests.rs +@@ -40,6 +40,8 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Top); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/raytrace/image.rs ++++ b/crates/render/src/raytrace/image.rs +@@ -1,2362 +1,2479 @@ +-//! 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::new(request.width, request.height, progressive.samples_per_pixel, options.budget)? { +- 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 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.preview_count()).checked_mul(checkpoint).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], +- light: usize, +- bounce: u8, +- throughput: Vec3, +- radiance: Vec3, +-} +- +-/// 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) { +- 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.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; +-} +- +-pub struct ImageTask { +- punctual_diagnostics: job::PunctualDiagnostics, +- progressive: Option, +- optical: Vec, +- anisotropic_targets: [Option; 2], +- environment: Option, +- scene: ProductScene, +- request: ImageRequest, +- options: RaytraceOptions, +- 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()?; +- 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, +- optical, +- anisotropic_targets, +- environment, +- scene, +- request, +- options, +- 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.scene.meshes.get(self.body) else { +- let triangles = std::mem::take(&mut self.triangles); +- let expected = BvhBuilder::required_bytes(triangles.len(), triangles.capacity(), limits(self.options.budget)).map_err(error)?; +- let builder = BvhBuilder::new(triangles, limits(self.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.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<()> { +- // 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.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.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<()> { +- // 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 { +- self.work.tick(&self.cancel).map_err(error)?; +- self.spatial_radiance += self.pixel_radiance / f64::from(self.sample_count()) / f64::from(self.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.options.primary_samples; +- return Ok(true); +- } +- if self.emit_spatial_pixel { +- self.work.tick(&self.cancel).map_err(error)?; +- let attempts = u16::from(self.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, self.primary_coverage, attempts, self.request.background, self.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.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.bounce != 0 +- || pending.hit.is_none() +- || self.sample == 0 +- || self.sample >= self.sample_count() +- || self.spatial >= self.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.options.punctual_lights.as_ref().map_or(0, Vec::len) +- || pending.area_light != self.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"))?; +- let shared = resolved_surface_hit(&PreparedScene { bvh, primitives: &self.looks, source: &self.scene }, pending, &self.effects)?; +- if self.optical.first().is_some_and(|o| o.pending.is_some()) +- || self.options.dielectrics.iter().any(|input| input.body_index == shared.body_index) +- { +- return Err(invalid("optical primary cannot reuse shading")); +- } +- if self.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.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.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.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], +- 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.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.options.dielectrics.len() { +- return Err(invalid("invalid primary certificate cursor")); +- } +- } +- let scene = PreparedScene { bvh, primitives: &self.looks, source: &self.scene }; +- 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.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.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.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.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.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"))?; +- pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, 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.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); +- if self.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"))?; +- pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); +- } else { +- pending.light = self.lights.lights().len(); +- } +- return Ok(()); +- } else if pending.light < self.lights.lights().len() { +- 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.options.punctual_lights.as_ref().map_or(0, Vec::len) { +- let shared = resolved_surface_hit(&scene, pending, &self.effects)?; +- let mode = +- self.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.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.options, bvh, (shared, target, mode), &mut self.work, &self.cancel, &mut self.punctual_diagnostics)?; +- return Ok(()); +- } +- if pending.area_light < self.options.area_lights.as_ref().map_or(0, Vec::len) { +- let shared = resolved_surface_hit(&scene, pending, &self.effects)?; +- let mode = +- self.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.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.options, +- bvh, +- (shared, target, mode), +- &mut self.work, +- &self.cancel, +- area_sample_key( +- self.pixel as u64, +- self.spatial, +- self.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.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.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.options, shared.body_index, face); +- if mode != Some(job::ReflectionMode::Mirror) { +- let visible = |index: usize, light: Vec3| { +- Ok(geometric.dot(light) > 0.0 && *pending.visibility.get(index).ok_or(TraceError::Internal("light visibility"))?) +- }; +- let direct = 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.options.reflections.as_ref().map_or(0, |r| r.max_bounces); +- if let Some(mode) = mode.filter(|_| pending.bounce < max_bounces) { +- let samples = self.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.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.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.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<()> { +- 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); +- 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<()> { +- 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.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.options.dielectrics.len(); +- } +- return Ok(()); +- } +- if state.selector != self.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.scene }; +- // 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.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.options.reflections.as_ref().and_then(|r| r.bodies.iter().find(|entry| entry.body == shared.body_name).map(|entry| entry.mode)); +- if self.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"))?; +- pending.cursor = TraceCursor::new(shared.spawn(light.direction()).map_err(error)?, true); +- } else { +- pending.light = self.lights.lights().len(); +- } +- return Ok(()); +- }; +- let medium = self.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.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); +- 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<()> { +- self.done = true; +- self.progressive = None; +- self.anisotropic_targets = [None, None]; +- self.options.anisotropic_faces = [None, None]; +- self.environment = None; +- self.scene.meshes = Vec::new(); +- 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.options.lights = None; +- self.options.emissions = None; +- self.emissions = Vec::new(); +- self.options.surface_effects = None; +- self.options.dielectrics = Vec::new(); +- self.options.environment = None; +- self.optical = Vec::new(); +- self.effects = Vec::new(); +- self.options.punctual_lights = None; +- self.options.area_lights = None; +- self.options.reflections = None; +- 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) +- } +- +- /// 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 covered = u16::try_from(covered).map_err(|_| error(TraceError::MemoryLimit))?; +- let count = u16::try_from(count).map_err(|_| error(TraceError::MemoryLimit))?; +- let [r, g, b] = linear_premultiplied; +- (composite_spatial(Vec3::new(r, g, b), covered, count, self.request.background, self.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.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 { +- self.work.tick(&self.cancel).map_err(error)?; +- let samples = progressive.film.samples(); +- if samples == progressive.options.samples_per_pixel || (progressive.partial_plan.is_none() && 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); +- } +- pixel +- .checked_mul(u64::from(job::MAX_CPU_SAMPLES_PER_PIXEL) * 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")) +-} +- +-fn composite_spatial(premultiplied: Vec3, covered: u16, attempts: u16, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { +- if attempts == 0 || u32::from(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; ++//! 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::new(request.width, request.height, progressive.samples_per_pixel, options.budget)? { ++ 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.preview_count()).checked_mul(checkpoint).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, ++ 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, ++ 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, self.primary_coverage, 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) ++ } ++ ++ /// 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 covered = u16::try_from(covered).map_err(|_| error(TraceError::MemoryLimit))?; ++ let count = u16::try_from(count).map_err(|_| error(TraceError::MemoryLimit))?; ++ 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 { ++ self.work.tick(&self.cancel).map_err(error)?; ++ let samples = progressive.film.samples(); ++ if samples == progressive.options.samples_per_pixel || (progressive.partial_plan.is_none() && 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); ++ } ++ pixel ++ .checked_mul(u64::from(job::MAX_CPU_SAMPLES_PER_PIXEL) * 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")) ++} ++ ++fn composite_spatial(premultiplied: Vec3, covered: u16, attempts: u16, background: [u8; 3], exposure: f64) -> job::Result<[u8; 4]> { ++ if attempts == 0 || u32::from(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; +--- a/crates/render/src/raytrace/image_tests.rs ++++ b/crates/render/src/raytrace/image_tests.rs +@@ -176,6 +176,8 @@ + } + fn request() -> ImageRequest { + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -419,7 +421,7 @@ + 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.scene.clone(), request, CancelToken::default(), options).unwrap(); ++ 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; +@@ -961,7 +963,8 @@ + ..Default::default() + }; + request.raytrace = Some(options.clone()); +- ImageTask::new(task.scene, request, cancel, options).unwrap() ++ let (fixture_scene, _) = task.visibility_owner.into_capture(); ++ ImageTask::new(fixture_scene, request, cancel, options).unwrap() + } + + #[test] +@@ -983,13 +986,13 @@ + #[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.scene.meshes[0].mesh); ++ 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.options.dielectrics.is_empty()); ++ assert!(task.visibility_owner.options().dielectrics.is_empty()); + assert!(task.request.raytrace.is_none()); + assert!(task.bvh.is_none()); + return; +@@ -1269,9 +1272,9 @@ + 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.scene.clone(); ++ let mut scene = task.visibility_owner.source().clone(); + let mut request = task.request.clone(); +- let mut options = task.options.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; +@@ -1298,8 +1301,10 @@ + if pending_branch { + task.optical[0].pending = Some(DielectricPixel::new(task.pending.as_ref().unwrap().ray)); + } else { +- task.options.dielectrics[0].body_index = 0; +- task.options.dielectrics[0].body_name = "Coupon".into(); ++ 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); +@@ -1391,7 +1396,7 @@ + assert_eq!(task.pending.0.capacity(), 1); + assert!(task.pending.is_none()); + assert!(std::mem::size_of::() <= 4096); +- let expected = admit(&task.scene, &task.request, &task.options).unwrap(); ++ 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; +@@ -1716,7 +1721,7 @@ + let mut film = None; + let mut primaries = Vec::new(); + let mut previous_sample = None; +- let target = task.options.progressive.unwrap().samples_per_pixel; ++ 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() +@@ -2084,7 +2089,7 @@ + } + + fn complete_straight_shells(mut task: ImageTask, expected_crossings: u8, expected_linear: [f64; 3]) -> Vec { +- let progressive = task.options.progressive; ++ let progressive = task.visibility_owner.options().progressive; + let mut final_linear = None; + let mut maximum = 0; + let mut final_png = None; +@@ -2593,8 +2598,8 @@ + } + + fn complete_long_tir(mut task: ImageTask, sigma: [f64; 3], strict: bool) -> Vec { +- let count = task.options.progressive.map_or(1, |p| p.samples_per_pixel) as usize; +- let progressive = task.options.progressive.is_some(); ++ 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]; +@@ -3014,3 +3019,560 @@ + // 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 { ++ 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); ++ } ++ } ++} +--- a/crates/render/src/raytrace/lighting.rs ++++ b/crates/render/src/raytrace/lighting.rs +@@ -137,6 +137,44 @@ + } + Ok(sum) + } ++ /// Sum direct lighting with independently completed RGB transmittance. ++ /// Ineligible lights never call `transmittance`. Each returned channel must ++ /// be finite in [0, 1]; errors propagate without clipping or a fallback. ++ /// No exposure, tone mapping, display encoding or indirect transport here. ++ pub(super) fn shade_linear_transmitted( ++ &self, ++ surface: OpaqueSurface, ++ normal: Vec3, ++ view: Vec3, ++ mut transmittance: impl FnMut(usize, Vec3) -> Result, ++ ) -> Result { ++ let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("finite nonzero shading normal required"))?; ++ let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("finite nonzero shading view required"))?; ++ let mut sum = Vec3::ZERO; ++ if n.dot(v) <= 0.0 { ++ return Ok(sum); ++ } ++ for (index, light) in self.lights.iter().enumerate() { ++ let cosine = n.dot(light.direction).max(0.0); ++ if cosine == 0.0 || light.intensity == 0.0 || light.color == Vec3::ZERO { ++ continue; ++ } ++ let transmission = transmittance(index, light.direction)?; ++ if !transmission.is_finite() || !channels(transmission).into_iter().all(|c| (0.0..=1.0).contains(&c)) { ++ return Err(TraceError::InvalidInput("direct transmittance must be finite RGB in [0, 1]")); ++ } ++ if transmission == Vec3::ZERO { ++ continue; ++ } ++ let brdf = surface.brdf(n, v, light.direction).map_err(|_| TraceError::InvalidInput("invalid opaque surface lighting directions"))?; ++ let weight = light.intensity * cosine; ++ let incident = Vec3::new(brdf.x * light.color.x, brdf.y * light.color.y, brdf.z * light.color.z) * weight; ++ sum += Vec3::new(incident.x * transmission.x, incident.y * transmission.y, incident.z * transmission.z); ++ validate_radiance(sum)?; ++ } ++ Ok(sum) ++ } ++ + } + + fn channels(v: Vec3) -> [f64; 3] { +--- a/crates/render/src/raytrace/lighting_tests.rs ++++ b/crates/render/src/raytrace/lighting_tests.rs +@@ -150,3 +150,139 @@ + // Expanding exposure never expands the admitted LINEAR transport bound. + assert!(map_to_display(Vec3::new(MAX_LINEAR_RADIANCE * 2.0, 0.0, 0.0), -32.0).is_err()); + } ++ ++#[test] ++fn transmitted_lambert_has_independent_analytic_colour_and_channel_weights() { ++ let light = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.25), PI).unwrap(); ++ let lighting = Lighting::new(vec![light]).unwrap(); ++ let actual = lighting ++ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| { ++ assert_eq!((index, direction), (0, Vec3::Z)); ++ Ok(Vec3::new(0.5, 0.25, 0.75)) ++ }) ++ .unwrap(); ++ // base(.8,.5,.25) * light(1,.5,.25) * PI/PI * T(.5,.25,.75). ++ assert!((actual - Vec3::new(0.4, 0.0625, 0.046875)).len() < 1e-14); ++} ++ ++#[test] ++fn transmitted_white_black_and_binary_visibility_preserve_boolean_shading() { ++ let lighting = Lighting::preset(StudioPreset::WarmCool).unwrap(); ++ for metallic in [0.0, 0.5, 1.0] { ++ let surface = OpaqueSurface::new(Vec3::new(0.8, 0.3, 0.2), metallic, 0.5, 1.5).unwrap(); ++ for selection in 0..3 { ++ let visible = |index: usize| match selection { 0 => false, 1 => true, _ => index % 2 == 0 }; ++ let old = lighting.shade_linear(surface, Vec3::Z, Vec3::Z, |i, _| Ok(visible(i))).unwrap(); ++ let rgb = lighting ++ .shade_linear_transmitted(surface, Vec3::Z, Vec3::Z, |i, _| { ++ Ok(if visible(i) { Vec3::new(1.0, 1.0, 1.0) } else { Vec3::ZERO }) ++ }) ++ .unwrap(); ++ assert_eq!(rgb, old); ++ } ++ } ++} ++ ++#[test] ++fn transmitted_two_lights_use_independent_indices_and_sum_before_output() { ++ let lighting = Lighting::new(vec![ ++ DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.0), PI).unwrap(), ++ DirectionalLight::new(Vec3::Z, Vec3::new(0.5, 0.0, 1.0), 2.0 * PI).unwrap(), ++ ]) ++ .unwrap(); ++ let mut visited = Vec::new(); ++ let actual = lighting ++ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| { ++ visited.push((index, direction)); ++ match index { ++ 0 => Ok(Vec3::new(0.25, 1.0, 0.5)), ++ 1 => Ok(Vec3::new(1.0, 0.5, 0.5)), ++ _ => panic!("unexpected light index"), ++ } ++ }) ++ .unwrap(); ++ assert_eq!(visited, vec![(0, Vec3::Z), (1, Vec3::Z)]); ++ // Light0=(.2,.25,0), light1=(.8,0,.25); no tone mapping or exposure. ++ assert!((actual - Vec3::new(1.0, 0.25, 0.25)).len() < 1e-14); ++} ++ ++#[test] ++fn transmitted_ineligible_lights_do_not_request_visibility_or_renumber_indices() { ++ let white = Vec3::new(1.0, 1.0, 1.0); ++ let lighting = Lighting::new(vec![ ++ DirectionalLight::new(Vec3::Z, white, 0.0).unwrap(), ++ DirectionalLight::new(-Vec3::Z, white, 1.0).unwrap(), ++ DirectionalLight::new(Vec3::Z, Vec3::ZERO, 1.0).unwrap(), ++ DirectionalLight::new(Vec3::X, white, 1.0).unwrap(), ++ DirectionalLight::new(Vec3::Z, white, PI).unwrap(), ++ ]) ++ .unwrap(); ++ let mut visited = Vec::new(); ++ let actual = lighting ++ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| { ++ assert_eq!((index, direction), (4, Vec3::Z)); ++ visited.push(index); ++ Ok(white) ++ }) ++ .unwrap(); ++ assert_eq!(visited, vec![4]); ++ assert!((actual - Vec3::new(0.8, 0.5, 0.25)).len() < 1e-14); ++ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, -Vec3::Z, |_, _| panic!("backfacing view")).unwrap(), Vec3::ZERO); ++ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::X, |_, _| panic!("tangent view")).unwrap(), Vec3::ZERO); ++ assert_eq!(Lighting::new(Vec::new()).unwrap().shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no lights")).unwrap(), Vec3::ZERO); ++} ++ ++#[test] ++fn transmitted_rejects_every_invalid_channel_and_propagates_callback_errors() { ++ let lighting = Lighting::new(vec![DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), PI).unwrap()]).unwrap(); ++ for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 1.01] { ++ for channel in 0..3 { ++ let transmittance = match channel { ++ 0 => Vec3::new(bad, 0.0, 0.0), ++ 1 => Vec3::new(0.0, bad, 0.0), ++ _ => Vec3::new(0.0, 0.0, bad), ++ }; ++ assert!(matches!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(transmittance)), Err(TraceError::InvalidInput(_)))); ++ } ++ } ++ for error in [TraceError::Cancelled, TraceError::WorkLimit, TraceError::MemoryLimit] { ++ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Err(error)), Err(error)); ++ } ++} ++ ++#[test] ++fn transmitted_keeps_shading_direction_validation_and_scale_normalization() { ++ let lighting = Lighting::new(vec![DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), PI).unwrap()]).unwrap(); ++ for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(0.0, 0.0, f64::INFINITY)] { ++ assert!(lighting.shade_linear_transmitted(lambert(), bad, Vec3::Z, |_, _| panic!("invalid normal")).is_err()); ++ assert!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, bad, |_, _| panic!("invalid view")).is_err()); ++ } ++ for magnitude in [1e-300, 1e308] { ++ let actual = lighting ++ .shade_linear_transmitted(lambert(), Vec3::new(0.0, 0.0, magnitude), Vec3::new(0.0, 0.0, magnitude), |_, _| Ok(Vec3::new(0.5, 0.25, 1.0))) ++ .unwrap(); ++ assert!((actual - Vec3::new(0.4, 0.125, 0.25)).len() < 1e-14); ++ } ++} ++ ++#[test] ++fn transmitted_checks_accumulated_radiance_after_transmission_without_clamping() { ++ // Hostile INTERNAL fixture deliberately bypasses DirectionalLight::new's ++ // intensity admission. This isolates the existing accumulated-radiance gate; ++ // these intensities are not asserted to be accepted by the public API. ++ // Each unattenuated term is (.6,.375,.1875)*MAX; two exceed MAX in red. ++ let light = DirectionalLight { direction: Vec3::Z, color: Vec3::new(1.0, 1.0, 1.0), intensity: 0.75 * PI * MAX_LINEAR_RADIANCE }; ++ let lighting = Lighting::new(vec![light, light]).unwrap(); ++ let mut visits = 0; ++ assert!(matches!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| { ++ visits += 1; ++ Ok(Vec3::new(1.0, 1.0, 1.0)) ++ }), Err(TraceError::InvalidInput(_)))); ++ assert_eq!(visits, 2); ++ let attenuated = lighting ++ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(Vec3::new(0.5, 0.5, 0.5))) ++ .unwrap(); ++ let expected = Vec3::new(0.6, 0.375, 0.1875) * MAX_LINEAR_RADIANCE; ++ assert!((attenuated - expected).len() <= MAX_LINEAR_RADIANCE * 1e-14); ++ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(Vec3::ZERO)).unwrap(), Vec3::ZERO); ++} +--- a/crates/render/src/raytrace/primary_aa_tests.rs ++++ b/crates/render/src/raytrace/primary_aa_tests.rs +@@ -8,12 +8,12 @@ + 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.options.clone(); ++ 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.scene.clone(), request, CancelToken::default(), options).unwrap() ++ ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() + } + + type ProgressiveOutput = (Vec<(u32, Vec)>, Vec, u64); +@@ -82,12 +82,12 @@ + 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.scene.clone(); +- let mut other = right.scene.meshes[0].clone(); ++ 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.options.clone(); ++ 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; +@@ -174,6 +174,8 @@ + ..Default::default() + }; + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -218,8 +220,8 @@ + 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.scene }.resolve_hit(p.ray, hit).unwrap(); +- if task.options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|b| b.body == shared.body_name)) { ++ 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"); + } + } +@@ -381,14 +383,15 @@ + #[test] + fn full_coverage_black_plane_never_leaks_display_background() { + for samples in [4, 16] { +- let mut initial = fixture(samples, 16, Some(true)); ++ 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 mesh = Arc::get_mut(&mut initial.scene.meshes[0].mesh).unwrap(); ++ 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); +- initial.scene.bounds = mesh.bounds(); +- let mut task = ImageTask::new(initial.scene, initial.request, initial.cancel, initial.options).unwrap(); ++ 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(); +@@ -425,13 +428,14 @@ + for samples in [4, 16] { + for left in [false, true] { + let mut initial = fixture(samples, 1, Some(left)); +- initial.scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()); +- initial.options.reflections = None; +- initial.options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [0.25, 0.5, 1.0], intensity: 2.0 }]); +- initial.options.exposure_ev = 1.0; ++ 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(initial.options.clone()); +- let mut task = ImageTask::new(initial.scene, initial.request, initial.cancel, initial.options).unwrap(); ++ 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, +@@ -456,11 +460,11 @@ + let cap = job::CpuBudget::Workstation.limits().max_samples_per_pixel; + assert_eq!(cap, 4096); + for samples in [2048, cap] { +- let mut options = fixed.options.clone(); ++ 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 task = ImageTask::new(fixed.scene.clone(), request, CancelToken::default(), options).unwrap(); ++ let task = ImageTask::new(fixed.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + let (previews, final_png, _) = progressive_complete(task, 16_384); + let expected: Vec<_> = (0..samples.ilog2()).map(|power| 1_u32 << power).collect(); + assert_eq!(previews.iter().map(|(n, _)| *n).collect::>(), expected); +@@ -495,7 +499,7 @@ + // 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.scene.clone(); ++ 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], +@@ -526,7 +530,7 @@ + + fn progressive_area_rebuild(source: &ImageTask, options: RaytraceOptions) -> ImageTask { + let request = ImageRequest { raytrace: Some(options.clone()), ..source.request.clone() }; +- ImageTask::new(source.scene.clone(), request, CancelToken::default(), options).unwrap() ++ ImageTask::new(source.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() + } + + #[test] +@@ -627,13 +631,13 @@ + }; + for count in [1, 4, 16, 64] { + let direct = progressive_area_fixture(count, 3, 7, true); +- let mut options = direct.options.clone(); ++ 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.options.seed; +- assert_eq!(options, direct.options); ++ 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)); + } +@@ -642,14 +646,14 @@ + #[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.options.clone(); ++ 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.options.area_lights.as_ref().unwrap().capacity(); ++ let slots = source.visibility_owner.options().area_lights.as_ref().unwrap().capacity(); + let bytes = (slots * std::mem::size_of::()) as u64; +- assert_eq!(source.options.retained_bytes().unwrap(), bytes); ++ 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] { +@@ -662,7 +666,7 @@ + let mut over = source.request.clone(); + over.width = 1025; + over.height = 1024; +- assert_eq!(admit(&source.scene, &over, &source.options).err().unwrap().code, ErrorCode::LimitExceeded); ++ assert_eq!(admit(source.visibility_owner.source(), &over, source.visibility_owner.options()).err().unwrap().code, ErrorCode::LimitExceeded); + } + + #[test] +@@ -759,6 +763,8 @@ + ..Default::default() + }; + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -828,7 +834,7 @@ + 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.options.progressive.unwrap().samples_per_pixel; ++ 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() +@@ -1003,19 +1009,20 @@ + #[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.options.clone(); ++ 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.scene, &request, &options, false, plan).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.scene, &request, &options, false, plan).unwrap(); ++ 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(fixed.scene, request, CancelToken::default(), options, None, false, plan).unwrap(); ++ 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(); +@@ -1047,10 +1054,10 @@ + 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.scene.clone(), ++ source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), +- source.options.clone(), ++ source.visibility_owner.options().clone(), + None, + false, + plan, +@@ -1079,9 +1086,9 @@ + #[test] + fn partial_hdr_rough_reflection_first_pass_and_final_match_legacy_sampling() { + let base = fixture(1, 1, Some(true)); +- let mut scene = base.scene.clone(); ++ 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.options.clone(); ++ 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(); +@@ -1148,15 +1155,15 @@ + } + + fn protected_plan(task: &ImageTask) -> job::ProtectedPreviewPlan { +- job::ProtectedPreviewPlan::new(task.request.width, task.request.height, task.options.progressive.unwrap().samples_per_pixel, task.options.budget) ++ 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.scene.clone(), ++ source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), +- source.options.clone(), ++ source.visibility_owner.options().clone(), + input, + false, + protected_plan(source), +@@ -1165,10 +1172,10 @@ + } + fn shared_partial_rebuild(source: &ImageTask, input: Option) -> ImageTask { + ImageTask::new_with_environment_and_nested_and_partial( +- source.scene.clone(), ++ source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), +- source.options.clone(), ++ source.visibility_owner.options().clone(), + input, + false, + protected_plan(source).preview_plan(), +@@ -1184,7 +1191,8 @@ + ..Default::default() + }; + let request = ImageRequest { width: 32, height: 32, background: [10, 20, 30], raytrace: Some(options.clone()), ..fixed.request }; +- ImageTask::new(fixed.scene, request, CancelToken::default(), options).unwrap() ++ 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"); +@@ -1431,27 +1439,27 @@ + 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.scene, &source.request, &source.options, false, plan).unwrap(); +- let shared = admit_with_partial_preview(&source.scene, &source.request, &source.options, false, plan.preview_plan()).unwrap(); ++ 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.options.budget).unwrap(), +- job::ProtectedPreviewPlan::new(4, 1, 3, source.options.budget).unwrap(), ++ 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.scene, &source.request, &source.options, false, wrong).err().unwrap().code, ++ 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.scene.clone(), ++ source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), +- source.options.clone(), ++ source.visibility_owner.options().clone(), + None, + false, + wrong +@@ -1462,7 +1470,7 @@ + ErrorCode::InvalidRequest + ); + } +- assert_eq!(source.options.emissions.as_ref().unwrap().len(), 1, "original fixture authors one red surface emission"); ++ 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!( +@@ -1491,7 +1499,9 @@ + assert_eq!(task.work.used(), control.work.used() + plan.snapshot_work().unwrap()); + } + let mut source = progressive_fixture(5, 23, Some(true), 0.0); +- source.scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.8, 0.4, 0.2), 1.0, 0.35, 1.5).unwrap()); ++ 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); +@@ -1661,8 +1671,8 @@ + } + + fn with_unit_optical_sheet(source: &ImageTask) -> (ProductScene, ImageRequest, RaytraceOptions) { +- let mut scene = source.scene.clone(); +- let mut options = source.options.clone(); ++ 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 { +@@ -1713,10 +1723,12 @@ + #[test] + fn progressive_unit_optics_rejoin_hdr_receiver_and_preserve_feedback_film_and_seed() { + let mut source = progressive_area_fixture(4, 3, 23, false); +- source.options.area_lights = None; +- source.options.area_samples = None; +- source.options.seed = None; +- source.request.raytrace = Some(source.options.clone()); ++ 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( +@@ -1751,10 +1763,10 @@ + 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.scene.clone(), ++ source.visibility_owner.source().clone(), + source.request.clone(), + CancelToken::default(), +- source.options.clone(), ++ source.visibility_owner.options().clone(), + Some(partial_original_hdr()), + ) + .unwrap(); +--- a/crates/render/src/raytrace/punctual_image_tests.rs ++++ b/crates/render/src/raytrace/punctual_image_tests.rs +@@ -44,6 +44,8 @@ + ..Default::default() + }; + let request = ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +@@ -92,12 +94,12 @@ + 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.options.clone(); ++ 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.scene.clone(), request, CancelToken::default(), options).unwrap(); ++ let actual = ImageTask::new(previous.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap(); + assert_eq!(render(actual), expected); + } + } +@@ -138,7 +140,7 @@ + + fn mixed(n: u32, shadows: bool) -> ImageTask { + let previous = task(None, shadows); +- let mut options = previous.options.clone(); ++ 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![ +@@ -154,7 +156,7 @@ + options.area_samples = Some(n); + let mut request = previous.request.clone(); + request.raytrace = Some(options.clone()); +- ImageTask::new(previous.scene.clone(), request, CancelToken::default(), options).unwrap() ++ ImageTask::new(previous.visibility_owner.source().clone(), request, CancelToken::default(), options).unwrap() + } + + #[test] +@@ -229,7 +231,7 @@ + #[test] + fn mixed_normal_incidence_radiance_is_summed_before_single_display_transform() { + let mut task = mixed(1, false); +- let options = &mut task.options; ++ 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]; +@@ -239,6 +241,7 @@ + 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); +@@ -250,14 +253,14 @@ + 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.options.clone(); ++ 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.scene.clone(), request, CancelToken::default(), options).unwrap(); ++ 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() { +--- a/crates/render/src/raytrace/reflection_image_tests.rs ++++ b/crates/render/src/raytrace/reflection_image_tests.rs +@@ -183,6 +183,8 @@ + let mut camera = crate::Camera { distance: 50.0, ..Default::default() }; + camera.set_view(crate::StandardView::Front); + ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/crates/render/src/studio.rs ++++ b/crates/render/src/studio.rs +@@ -76,6 +76,124 @@ + Ok(radiance) + } + ++/// Shared slots for points and spots, independently of directional slots. ++pub const MAX_SCHEMATIC_PUNCTUAL_LIGHTS: usize = 8; ++pub const MAX_SCHEMATIC_RECTANGLE_LIGHTS: usize = 4; ++ ++/// Unshadowed numerical response for the bounded opaque Raster consumer. ++/// ++/// Valid inputs use borrowed slices without new containers or retained allocations. ++/// Invalid DTOs may allocate the existing validator's bounded error String. ++/// The caller must separately admit the ++/// retained capacities/copies and charge up to twenty BRDF evaluations per ++/// sample; these slice bounds are not a memory or cancellation admission. ++/// An empty rig is dark. No implicit studio, exposure or display transfer. ++/// ++/// Points use reference-distance inverse-square falloff with the authored ++/// minimum distance. Spots use a cubic smoothstep in cosine space (an interval ++/// <= 1e-6 uses the outer-cosine step). Rectangles use ONLY the centre, projected ++/// area and emitting U-cross-V normal; aspect ratio at fixed area has no effect. ++/// No finite-footprint integration, soft shadows, sampling seed or environment. ++/// Coincident source/sample contributes zero, as in the paired Model helper. ++/// Source alignment is not executed f64/f32 image or physical-parity acceptance. ++pub fn shade_schematic( ++ surface: OpaqueSurface, ++ normal: Vec3, ++ view: Vec3, ++ position_mm: Vec3, ++ directional: &[crate::job::DirectionalLightOptions], ++ punctual: &[crate::job::PunctualLightOptions], ++ rectangles: &[crate::job::RectangleLightOptions], ++) -> Result { ++ if directional.len() > MAX_SCHEMATIC_DIRECTIONAL_LIGHTS ++ || punctual.len() > MAX_SCHEMATIC_PUNCTUAL_LIGHTS ++ || rectangles.len() > MAX_SCHEMATIC_RECTANGLE_LIGHTS ++ || !schematic_world_point(position_mm) ++ { ++ return Err(SurfaceError::Radiance); ++ } ++ // Reuse the real public DTO validator; no shadow parser or CPU feature gate. ++ // Check all local inputs before visibility, colour or intensity can skip one. ++ for light in punctual { ++ light.validate().map_err(|_| SurfaceError::Radiance)?; ++ } ++ for light in rectangles { ++ schematic_rectangle_geometry(light)?; ++ } ++ let n = unit_direction(normal)?; ++ let v = unit_direction(view)?; ++ // Keep the existing directional implementation and its validation intact. ++ let mut radiance = shade_directional(surface, n, v, directional)?; ++ for light in punctual { ++ let [x, y, z] = light.position_mm; ++ let delta = Vec3::new(x, y, z) - position_mm; ++ if delta == Vec3::ZERO { ++ continue; ++ } ++ let direction = unit_direction(delta)?; ++ let distance_squared = delta.dot(delta).max(light.minimum_distance_mm * light.minimum_distance_mm).max(1e-6); ++ let mut weight = light.reference_distance_mm * light.reference_distance_mm / distance_squared; ++ if let Some(cone) = light.cone { ++ let [x, y, z] = cone.emitted_axis; ++ let cosine = unit_direction(Vec3::new(x, y, z))?.dot(-direction); ++ let inner = cone.inner_half_angle_radians.cos(); ++ let outer = cone.outer_half_angle_radians.cos(); ++ let profile = if inner - outer > 1e-6 { ++ let t = ((cosine - outer) / (inner - outer)).clamp(0.0, 1.0); ++ t * t * (3.0 - 2.0 * t) ++ } else if cosine >= outer { ++ 1.0 ++ } else { ++ 0.0 ++ }; ++ weight *= profile; ++ } ++ radiance += schematic_contribution(surface, n, v, direction, light.color, light.intensity * weight)?; ++ } ++ for light in rectangles { ++ let (center, emitting_normal, area) = schematic_rectangle_geometry(light)?; ++ let delta = center - position_mm; ++ if delta == Vec3::ZERO { ++ continue; ++ } ++ let direction = unit_direction(delta)?; ++ let weight = area * emitting_normal.dot(-direction).max(0.0) / delta.dot(delta).max(1e-6); ++ radiance += schematic_contribution(surface, n, v, direction, light.color, light.intensity * weight)?; ++ } ++ if !radiance.is_finite() || radiance.x < 0.0 || radiance.y < 0.0 || radiance.z < 0.0 { ++ return Err(SurfaceError::Radiance); ++ } ++ Ok(radiance) ++} ++ ++fn schematic_world_point(point: Vec3) -> bool { ++ point.is_finite() && [point.x, point.y, point.z].into_iter().all(|c| c.abs() <= 1e9) ++} ++ ++// The crate-local rectangle validator is shared with CPU transport and admission. ++// This geometry projection does not parse or admit retained containers. ++fn schematic_rectangle_geometry(light: &crate::job::RectangleLightOptions) -> Result<(Vec3, Vec3, f64), SurfaceError> { ++ light.validate().map_err(|_| SurfaceError::Radiance)?; ++ let [x, y, z] = light.center_mm; ++ let center = Vec3::new(x, y, z); ++ let [x, y, z] = light.edge_u_mm; ++ let u = Vec3::new(x, y, z); ++ let [x, y, z] = light.edge_v_mm; ++ let v = Vec3::new(x, y, z); ++ let cross = u.cross(v); ++ Ok((center, unit_direction(cross)?, cross.len())) ++} ++ ++fn schematic_contribution(surface: OpaqueSurface, normal: Vec3, view: Vec3, direction: Vec3, color: [f64; 3], incident: f64) -> Result { ++ let brdf = surface.brdf(normal, view, direction)?; ++ let [r, g, b] = color; ++ let value = Vec3::new(brdf.x * r, brdf.y * g, brdf.z * b) * (incident * normal.dot(direction).max(0.0)); ++ if !value.is_finite() || value.x < 0.0 || value.y < 0.0 || value.z < 0.0 { ++ return Err(SurfaceError::Radiance); ++ } ++ Ok(value) ++} ++ + /// Per-channel Reinhard preview tone map, still in linear sRGB. + /// Consumers encode exactly once after applying this to nonnegative finite radiance. + pub fn tone_map(radiance: Vec3) -> Result { +@@ -210,4 +328,253 @@ + assert!((old - new).len() < 1e-14); + } + } +-} ++ ++ fn local_surface() -> OpaqueSurface { ++ OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap() ++ } ++ ++ fn local_point() -> crate::job::PunctualLightOptions { ++ crate::job::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 local_rectangle() -> crate::job::RectangleLightOptions { ++ crate::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: 2.0, ++ } ++ } ++ ++ fn assert_lambert(value: Vec3, incident_cosine: f64) { ++ // Closed-form rho/pi, independent of the production light helper. ++ let expected = Vec3::new(0.8, 0.5, 0.25) * (incident_cosine / PI); ++ assert!((value - expected).len() < 1e-12 * expected.len().max(1.0), "{value:?} != {expected:?}"); ++ } ++ ++ #[test] ++ fn schematic_local_point_reference_and_double_distance_match_closed_form() { ++ let mut point = local_point(); ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), 2.0); ++ point.position_mm = [0.0, 0.0, 20.0]; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), 0.5); ++ } ++ ++ #[test] ++ fn schematic_local_point_colour_and_receiver_cosine_are_linear() { ++ let mut point = local_point(); ++ point.position_mm = [0.0, 6.0, 8.0]; ++ point.color = [0.25, 0.5, 1.0]; ++ let value = shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(); ++ let expected = Vec3::new(0.32, 0.4, 0.4) * (1.0 / PI); ++ assert!((value - expected).len() < 1e-13); ++ } ++ ++ #[test] ++ fn schematic_local_world_translation_preserves_point_spot_and_rectangle_response() { ++ let mut point = local_point(); ++ point.cone = Some(crate::job::SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); ++ let mut rectangle = local_rectangle(); ++ let first = shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[rectangle.clone()]).unwrap(); ++ point.position_mm = [123.0, -45.0, 77.0]; ++ rectangle.center_mm = point.position_mm; ++ let moved = shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::new(123.0, -45.0, 67.0), &[], &[point], &[rectangle]).unwrap(); ++ assert!((first - moved).len() < 1e-13); ++ } ++ ++ #[test] ++ fn schematic_local_minimum_distance_and_tiny_nonzero_delta_remain_finite() { ++ let mut point = local_point(); ++ point.position_mm = [0.0, 0.0, 1.0]; ++ point.minimum_distance_mm = 2.0; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), 50.0); ++ point.position_mm = [0.0, 0.0, 1e-200]; ++ point.minimum_distance_mm = 0.001; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), 2e8); ++ } ++ ++ #[test] ++ fn schematic_local_spot_inner_outer_and_cosine_midpoint_match_cubic_profile() { ++ // Source at +Z: these axes have cosine 1, -1 or 1/2 with -Z. ++ // cos(inner)=4/5 and cos(outer)=1/5, so cosine1/2 gives t=1/2. ++ for (axis, expected) in [([0.0, 0.0, -1.0], 2.0), ([0.0, 0.0, 1.0], 0.0), ([3.0_f64.sqrt(), 0.0, -1.0], 1.0)] { ++ let mut point = local_point(); ++ point.cone = Some(crate::job::SpotConeOptions { ++ emitted_axis: axis, ++ inner_half_angle_radians: 0.8_f64.acos(), ++ outer_half_angle_radians: 0.2_f64.acos(), ++ }); ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), expected); ++ } ++ } ++ ++ #[test] ++ fn schematic_local_spot_narrow_interval_uses_explicit_step_policy() { ++ for (axis, expected) in [([0.0, 0.0, -1.0], 2.0), ([1.0, 0.0, 0.0], 0.0)] { ++ let mut point = local_point(); ++ point.cone = Some(crate::job::SpotConeOptions { emitted_axis: axis, inner_half_angle_radians: 0.0, outer_half_angle_radians: 0.001 }); ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), expected); ++ } ++ } ++ ++ #[test] ++ fn schematic_local_area_centroid_matches_area_over_squared_distance() { ++ let mut rectangle = local_rectangle(); ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle.clone()]).unwrap(), 0.08); ++ rectangle.edge_u_mm = [4.0, 0.0, 0.0]; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle.clone()]).unwrap(), 0.16); ++ rectangle.center_mm = [0.0, 0.0, 20.0]; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).unwrap(), 0.04); ++ } ++ ++ #[test] ++ fn schematic_local_area_emitting_side_and_projected_cosine_are_explicit() { ++ let mut rectangle = local_rectangle(); ++ rectangle.edge_v_mm = [0.0, -1.6, -1.2]; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle.clone()]).unwrap(), 0.064); ++ rectangle.edge_v_mm = [0.0, 2.0, 0.0]; ++ assert_eq!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).unwrap(), Vec3::ZERO); ++ } ++ ++ #[test] ++ fn schematic_local_area_same_area_different_aspect_is_documented_approximation() { ++ let rectangle = local_rectangle(); ++ let mut thin = rectangle.clone(); ++ thin.edge_u_mm = [4.0, 0.0, 0.0]; ++ thin.edge_v_mm = [0.0, -1.0, 0.0]; ++ let first = shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).unwrap(); ++ let second = shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[thin]).unwrap(); ++ assert_eq!(first, second); ++ } ++ ++ #[test] ++ fn schematic_local_coincident_point_spot_and_area_are_zero_without_fallback_axis() { ++ let mut point = local_point(); ++ point.position_mm = [0.0; 3]; ++ let mut rectangle = local_rectangle(); ++ rectangle.center_mm = [0.0; 3]; ++ for cone in [None, Some(crate::job::SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 })] { ++ point.cone = cone; ++ assert_eq!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[rectangle.clone()]).unwrap(), Vec3::ZERO); ++ } ++ } ++ ++ #[test] ++ fn schematic_local_empty_back_facing_and_back_view_have_no_ambient() { ++ assert_eq!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[]).unwrap(), Vec3::ZERO); ++ let point = local_point(); ++ for (n, v) in [(-Vec3::Z, Vec3::Z), (Vec3::Z, -Vec3::Z)] { ++ assert_eq!(shade_schematic(local_surface(), n, v, Vec3::ZERO, &[], &[point], &[]).unwrap(), Vec3::ZERO); ++ } ++ } ++ ++ #[test] ++ fn schematic_local_three_families_superpose_without_display_transfer() { ++ let d = directional([0.0, 0.0, 1.0], [1.0; 3], 1.0); ++ let value = shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[d], &[local_point()], &[local_rectangle()]).unwrap(); ++ assert_lambert(value, 3.08); ++ assert_ne!(value, tone_map(value).unwrap()); ++ } ++ ++ #[test] ++ fn schematic_local_counts_eight_shared_punctual_and_four_rectangles_separately() { ++ let d: [_; 8] = std::array::from_fn(|_| directional([0.0, 0.0, 1.0], [1.0; 3], 1.0)); ++ let mut p = [local_point(); 8]; ++ p[7].cone = Some(crate::job::SpotConeOptions { emitted_axis: [0.0, 0.0, -1.0], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); ++ let a: [_; 4] = std::array::from_fn(|_| local_rectangle()); ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &d, &p, &a).unwrap(), 24.32); ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &d, &[local_point(); 9], &a).is_err()); ++ let five: [_; 5] = std::array::from_fn(|_| local_rectangle()); ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &d, &p, &five).is_err()); ++ let nine: [_; 9] = std::array::from_fn(|_| directional([0.0, 0.0, 1.0], [1.0; 3], 1.0)); ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &nine, &p, &a).is_err()); ++ } ++ ++ #[test] ++ fn schematic_local_dark_coincident_inputs_still_validate_every_punctual_property() { ++ let mut dark = local_point(); ++ dark.color = [0.0; 3]; ++ dark.intensity = 0.0; ++ dark.position_mm = [0.0; 3]; ++ for bad in [f64::NAN, f64::INFINITY, 0.0, 1e6 + 1.0] { ++ let mut point = dark; ++ point.reference_distance_mm = bad; ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).is_err()); ++ } ++ let mut point = dark; ++ point.cone = Some(crate::job::SpotConeOptions { emitted_axis: [0.0; 3], inner_half_angle_radians: 0.2, outer_half_angle_radians: 0.5 }); ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).is_err()); ++ point = dark; ++ point.position_mm = [f64::NAN, 0.0, 0.0]; ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).is_err()); ++ } ++ ++ #[test] ++ fn schematic_local_dark_rectangles_refuse_bad_lengths_axes_corners_and_radiance() { ++ let mut dark = local_rectangle(); ++ dark.color = [0.0; 3]; ++ dark.intensity = 0.0; ++ for edge in [[0.0; 3], [f64::NAN, 0.0, 0.0], [f64::INFINITY, 0.0, 0.0], [1e-7, 0.0, 0.0], [1e6 + 1.0, 0.0, 0.0], [1.0, 1.0, 0.0]] { ++ let mut rectangle = dark.clone(); ++ rectangle.edge_u_mm = edge; ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).is_err()); ++ } ++ for bad in [f64::NAN, f64::INFINITY, -1.0, 64.01] { ++ let mut rectangle = dark.clone(); ++ rectangle.intensity = bad; ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).is_err()); ++ } ++ let mut rectangle = dark; ++ rectangle.center_mm = [1e9, 0.0, 0.0]; ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).is_err()); ++ } ++ ++ #[test] ++ fn schematic_local_rejects_bad_sample_position_and_directions_even_when_empty() { ++ for p in [Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(f64::INFINITY, 0.0, 0.0), Vec3::new(1e9 + 1.0, 0.0, 0.0)] { ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, p, &[], &[], &[]).is_err()); ++ } ++ assert!(shade_schematic(local_surface(), Vec3::ZERO, Vec3::Z, Vec3::ZERO, &[], &[], &[]).is_err()); ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::ZERO, Vec3::ZERO, &[], &[], &[]).is_err()); ++ let bad = directional([0.0; 3], [0.0; 3], 0.0); ++ assert!(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[bad], &[], &[]).is_err()); ++ } ++ ++ #[test] ++ fn schematic_local_finite_maximum_authored_scales_are_not_silently_clipped() { ++ let mut point = local_point(); ++ point.position_mm = [0.0, 0.0, 0.001]; ++ point.reference_distance_mm = 1e6; ++ point.intensity = 64.0; ++ let mut rectangle = local_rectangle(); ++ rectangle.center_mm = point.position_mm; ++ rectangle.edge_u_mm = [1e6, 0.0, 0.0]; ++ rectangle.edge_v_mm = [0.0, -1e6, 0.0]; ++ rectangle.intensity = 64.0; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[rectangle]).unwrap(), 1.28e20); ++ } ++ ++ #[test] ++ fn schematic_local_area_floor_and_spot_cosine_endpoints_are_explicit() { ++ let mut rectangle = local_rectangle(); ++ rectangle.center_mm = [0.0, 0.0, 0.0001]; ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[], &[rectangle]).unwrap(), 8e6); ++ for (cosine, expected) in [(0.8_f64, 2.0), (0.2_f64, 0.0)] { ++ let mut point = local_point(); ++ point.cone = Some(crate::job::SpotConeOptions { ++ emitted_axis: [(1.0 - cosine * cosine).sqrt(), 0.0, -cosine], ++ inner_half_angle_radians: 0.8_f64.acos(), ++ outer_half_angle_radians: 0.2_f64.acos(), ++ }); ++ assert_lambert(shade_schematic(local_surface(), Vec3::Z, Vec3::Z, Vec3::ZERO, &[], &[point], &[]).unwrap(), expected); ++ } ++ } ++} +--- a/crates/ui-egui/src/render_workspace_library.rs ++++ b/crates/ui-egui/src/render_workspace_library.rs +@@ -944,6 +944,36 @@ + }) + } + ++/// Explicit staging is separate from scalar Apply and the blocked glass tile. ++pub(super) fn stage_glass(app: &mut SolveApp, id: &str) -> Result<(), String> { ++ materials::stage_library_glass(app, id)?; ++ app.render_workspace.view.selection = super::RenderSelection::Object(app.session.selection.clone()); ++ app.render_workspace.view.inspector.page = super::inspector::Page::Appearance; ++ app.render_workspace.view.dirty = true; ++ app.set_status(app.tr("render.glass_library_prepared").to_string(), false); ++ Ok(()) ++} ++ ++fn glass_route_controls(app: &mut SolveApp, ui: &mut egui::Ui, view: &View) { ++ if view.kind != "appearances" { ++ return; ++ } ++ let Some(id) = view.selected.as_deref().filter(|id| { ++ solidcraft_engine::doc::appearance_pack::find(id) ++ .is_some_and(|preset| preset.id == *id && matches!(preset.recipe, solidcraft_engine::doc::appearance_pack::Recipe::Glass(_))) ++ }) else { return }; ++ ui_kit::text(ui, app.tr("render.glass_library_help"), ui_kit::Text::Note("render:library:glass-help")); ++ let ready = materials::library_glass_ready(app, id); ++ let action = ui_kit::button(ui, app.tr("render.glass_library_edit"), ui_kit::Button::Enabled(ready.is_ok())); ++ crate::scenario::publish_target("render:library:prepare-glass", action.rect); ++ if let Err(reason) = &ready { ++ ui_kit::text(ui, reason, ui_kit::Text::Note("render:library:glass-reason")); ++ } ++ if action.clicked() && let Err(error) = stage_glass(app, id) { ++ app.set_status(error, true); ++ } ++} ++ + fn browse_contents(app: &mut SolveApp, ui: &mut egui::Ui, stage_card: bool) { + let mut view = std::mem::take(&mut app.render_workspace.view.library); + let document_changed = +@@ -1246,6 +1276,7 @@ + } + } + if stage_card { ++ glass_route_controls(app, ui, &view); + ui_kit::catalog_footer_with_tip(ui, app.tr("render.stage_layout.appearance_note"), app.tr("render.assign_help")); + if view.kind == "materials" { + ui_kit::text(ui, app.tr("render.library_specification_only"), ui_kit::Text::Note("appearance:reference:reason")); +--- a/crates/ui-egui/src/render_workspace_materials.rs ++++ b/crates/ui-egui/src/render_workspace_materials.rs +@@ -706,6 +706,113 @@ + + /// Prepare through the engine, then install only a request-local binding. No + /// authored material may silently remove a glass override or switch executor. ++/// Read-only eligibility for an explicit catalogue action, not a certificate. ++pub(super) fn library_glass_ready(app: &SolveApp, id: &str) -> Result<(), String> { ++ if !matches!(app.render_workspace.view.method, super::ImageMethod::CpuRaytrace | super::ImageMethod::GpuRaytrace) { ++ return Err(app.tr("render.glass_library_method").into()); ++ } ++ if id.is_empty() || id.len() > 128 { ++ return Err(app.tr("render.error_glass_recipe").into()); ++ } ++ let preset = appearance_pack::find(id).filter(|preset| preset.id == id) ++ .ok_or_else(|| app.tr("render.error_glass_recipe").to_string())?; ++ if !matches!(preset.recipe, Recipe::Glass(_)) { ++ return Err(app.tr("render.error_physical_glass").into()); ++ } ++ let [solidcraft_engine::Sel::Body { name }] = app.session.selection.as_slice() else { ++ return Err(app.tr("render.appearance_editor.body_reason").into()); ++ }; ++ if name.is_empty() || name.len() > 1024 || name.chars().any(char::is_control) || !app.session.body_visible(name) { ++ return Err(app.tr("render.material_target_missing").into()); ++ } ++ if app.session.model.is_stale() { ++ return Err(app.tr("render.material_revalidate_needed").into()); ++ } ++ let bindings = &app.render_workspace.view.materials.bindings; ++ let mut matching = bindings.iter().filter(|binding| binding.target.name == *name); ++ let existing = matching.next(); ++ if matching.next().is_some() { ++ return Err(app.tr("render.glass_library_conflict").into()); ++ } ++ if bindings.len() > MAX_BINDINGS || (existing.is_none() && bindings.len() == MAX_BINDINGS) { ++ return Err(app.tr("render.material_limits").into()); ++ } ++ if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace ++ && existing.is_none_or(|binding| !binding.active()) ++ && bindings.iter().filter(|binding| binding.active()).count() >= 8 ++ { ++ return Err(app.tr("render.cpu_optics_limit").into()); ++ } ++ Ok(()) ++} ++ ++fn same_library_glass(a: &Glass, b: &Glass) -> bool { ++ a.recipe == b.recipe && a.ior == b.ior && a.absorption == b.absorption ++ && a.boundary == b.boundary && a.thickness == b.thickness ++ && a.shadows == b.shadows && a.subsurface.is_none() && b.subsurface.is_none() ++} ++ ++/// Stage authored values in the existing editor. No appearance assignment, ++/// implicit CPU permission, boundary inference, geometry certification or save. ++pub(super) fn stage_library_glass(app: &mut SolveApp, id: &str) -> Result<(), String> { ++ library_glass_ready(app, id)?; ++ let glass = Glass::recipe(id)?; // The one existing validated conversion. ++ let [solidcraft_engine::Sel::Body { name }] = app.session.selection.as_slice() else { ++ return Err(app.tr("render.appearance_editor.body_reason").into()); ++ }; ++ let name = name.clone(); ++ let revision = app.session.revision; ++ let document = Arc::downgrade(&app.session.doc); ++ let targets = read_targets(app)?; ++ if revision != app.session.revision || !Weak::ptr_eq(&document, &Arc::downgrade(&app.session.doc)) || app.session.model.is_stale() { ++ return Err(app.tr("render.material_revalidate_needed").into()); ++ } ++ let mut matching = targets.into_iter().filter(|target| target.name == name); ++ let target = matching.next().ok_or_else(|| app.tr("render.material_target_missing").to_string())?; ++ if matching.next().is_some() { ++ return Err(app.tr("render.material_target_missing").into()); ++ } ++ target.stable_target.as_ref().ok_or_else(|| app.tr("render.material_target_missing").to_string())? ++ .validate().map_err(|error| error.to_string())?; ++ let existing = app.render_workspace.view.materials.bindings.iter().position(|binding| binding.target.name == name); ++ let binding = if let Some(index) = existing { ++ let old = app.render_workspace.view.materials.bindings.get(index) ++ .ok_or_else(|| app.tr("render.error_material_binding").to_string())?; ++ if old.target != target || !old.current(app) { ++ return Err(app.tr("render.material_revalidate_needed").into()); ++ } ++ if old.coat_enabled || old.maps_enabled { ++ return Err(app.tr("render.glass_library_conflict").into()); ++ } ++ if same_library_glass(&old.glass, &glass) { ++ return Ok(()); // An exact repeat preserves ALL existing opt-ins and disabled state. ++ } ++ if old.glass_enabled || !same_library_glass(&old.glass, &Glass::default()) { ++ return Err(app.tr("render.glass_library_conflict").into()); ++ } ++ old.clone() // An empty existing slot retains its other authored fields/permission. ++ } else { ++ Binding::new(target, app) // New CPU permission remains false. ++ }; ++ let mut binding = binding; ++ binding.glass = glass; ++ binding.glass_enabled = true; ++ let view = &mut app.render_workspace.view.materials; ++ if let Some(index) = existing { ++ let slot = view.bindings.get_mut(index).ok_or_else(|| crate::i18n::tr("render.error_material_binding").to_string())?; ++ *slot = binding; ++ } else { ++ let was_empty = view.bindings.is_empty(); ++ view.bindings.try_reserve_exact(1).map_err(|_| crate::i18n::tr("render.material_limits").to_string())?; ++ view.bindings.push(binding); ++ if was_empty { ++ view.enabled = true; ++ } ++ // A previously disabled nonempty group is never reactivated by staging. ++ } ++ Ok(()) ++} ++ + pub(super) fn install_library_surface(app: &mut SolveApp, id: &str, target: Target, plane: &str, scale: f64) -> Result<(), String> { + if app.render_workspace.view.method != super::ImageMethod::GpuRaytrace { + return Err(app.tr("render.material_gpu_required").into()); +--- a/crates/ui-egui/src/render_workspace_tests.rs ++++ b/crates/ui-egui/src/render_workspace_tests.rs +@@ -1211,6 +1211,8 @@ + 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, +@@ -3620,6 +3622,8 @@ + 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, +@@ -8609,6 +8613,8 @@ + 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, +@@ -10852,3 +10858,235 @@ + 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}"); ++ } ++ } ++ } ++} +--- a/crates/ui-egui/src/render_workspace_thumbnails.rs ++++ b/crates/ui-egui/src/render_workspace_thumbnails.rs +@@ -138,6 +138,8 @@ + let permit = WorkerPermit; + let Some(setup) = app.session.doc.render.setups.get(&key.name) else { return }; + let request = solidcraft_engine::render::job::ImageRequest { ++ raster_punctual_lights: None, ++ raster_area_lights: None, + raster_exposure_ev: 0.0, + raster_lights: None, + studio_weights: None, +--- a/docs/render-cpu-progressive.md ++++ b/docs/render-cpu-progressive.md +@@ -63,7 +63,7 @@ + + ## Supported combinations and limits + +-| Control | Initial CPU progressive contract | ++| Control | CPU progressive contract | + | --- | --- | + | Dimensions | Each side 1..4096; at most 1,048,576 pixels | + | Samples per pixel | 1..64 | +@@ -74,11 +74,18 @@ + | Constant / captured HDR environment | Existing CPU contracts; HDR plus rough reflections still requires certified fully metallic selected bodies and effective faces | + | Surface emission / isotropic surface effects | Existing CPU appearance contracts; emission is visible radiance | + | Area / LED sources | Existing bounded rectangle direct-light transport; continuous LED recipes lower to the same sources | +-| Dielectric / anisotropic face overrides | Explicitly rejected in this initial progressive mode | ++| Dielectric overrides | Smooth `thin_sheet` / `closed_box` intent retained; capture certifies geometry, identity and supported combinations | ++| Anisotropic face overrides | Explicitly rejected in progressive mode; use fixed sampling | + | Output | Opaque PNG with the existing display background | + + An incompatible request fails; it does not remove settings or switch methods. + The fixed CPU route retains its existing area, dielectric and anisotropy support. ++Numerically valid dielectric selectors also survive progressive and Interactive ++lowering for capture-time certification. Successful lowering is not scene or job ++admission: existing boundary tessellation, captured identity, opacity, camera, ++medium and transport-policy limits still apply. The same dielectric body cannot ++also select opaque reflection, anisotropy, surface emission or nonidentity surface ++effects. Unsupported combinations remain errors; no general glass path is added. + Progressive area/LED uses at most four shared rectangle slots, with + `area_samples` of 1/4/16/64 (default 16) and the existing combined light caps. + Each film pass uses the existing area-power normalization and cumulative work +--- a/docs/render-raytrace-dielectrics.md ++++ b/docs/render-raytrace-dielectrics.md +@@ -21,7 +21,11 @@ + Preview / Image / PNG profile, and CPU requests containing dielectric overrides + require that capability during both preflight and host submission. This is the + bounded `thin_sheet` / `closed_box` contract below: it does not advertise general +-closed-mesh transmission, final-quality rendering or progressive CPU images. ++closed-mesh transmission or final-quality rendering. Fixed and CPU progressive ++sampling can retain this smooth-boundary intent; progressive sampling still ++requires one primary and one selected reflection attempt per camera sample. ++Interactive retains the same intent for capture-time certification, not as a ++guarantee that a scene or job will be admitted. + Raster and the cooperative CPU host do not advertise this capability. The + `render.backends` registry publishes the additional `cpu-raytrace` descriptor only + for an installed native CPU worker with the build feature enabled. Raster remains +@@ -56,6 +60,15 @@ + face flag select the interface; interpolated shading normals do not bend rays. + Parallel slab entry/exit produces the Snell lateral displacement within this + certified subset. This does not certify arbitrary CAD tessellations. ++ ++Successful request lowering is not a geometry certificate. Existing captured ++identity, body/face opacity, camera, medium, work and selected transport-policy ++checks remain authoritative. A dielectric boundary cannot also select opaque ++reflection, anisotropy, surface emission or nonidentity surface effects on that ++same body. Retaining the original selectors never removes those incompatible ++effects to make admission succeed. The transport details below retain the ++legacy bounded-preview qualifications; explicit transport options keep their ++existing separate validation and limits. + + `thin_sheet` accepts one nondegenerate planar triangle or two consistently wound, + coplanar triangles sharing one unique edge and lying on opposite sides of it. +--- a/tools/render-library/native_smoke.rs ++++ b/tools/render-library/native_smoke.rs +@@ -57,7 +57,7 @@ + fn request(root: &Path) -> Result> { + let hdr = HdrSource::new(fs::read(root.join("assets/render/starter/environments/exports/neutral-side-softbox.hdr"))?)?; + let environment = EnvironmentSource::from_hdr(hdr, std::f64::consts::PI, 1.0, false)?; +- Ok(ImageRequest { raster_exposure_ev: 0.0, raster_lights: None, ++ Ok(ImageRequest { raster_punctual_lights: None, raster_area_lights: None, raster_exposure_ev: 0.0, raster_lights: None, studio_weights: None, + camera: Camera { distance: 220.0, ..Default::default() }, + width: 320, + height: 240, diff --git a/proposals/render/2026-10-31/c22-composed-source/source-bindings.json b/proposals/render/2026-10-31/c22-composed-source/source-bindings.json new file mode 100644 index 000000000..770861ed3 --- /dev/null +++ b/proposals/render/2026-10-31/c22-composed-source/source-bindings.json @@ -0,0 +1,591 @@ +{ + "status": "ADOPTED_SOURCE_ONLY_UNFORMATTED_UNCOMPILED_UNRUN", + "base": { + "label": "actual frozen C21 source, not bare HEAD", + "HEAD": "a077906234972dbbf11e80c54893f85ece97c8b7", + "source_manifest_sha256": "5c336edc8bcda9252a85badcc8baf8ba7934291f76084f677745c63a7163e8de", + "source_members": 3580 + }, + "adopted_C22_source_manifest_sha256": "3ce571ff684706e3d62642807a1ba9487a589c6fdd45294ddc7b3e8c16532c67", + "adopted_source_members": 3581, + "changed_paths": 43, + "new_files": 1, + "files": [ + { + "path": "assets/locales/pending/render-glass-library-route.json", + "before_exists": false, + "before_bytes": null, + "before_sha256": null, + "candidate_bytes": 7753, + "candidate_sha256": "c5c6695b5df44d5093cf0b2aa6e474c8d7b1a6101c5f0c11b12d0de6934d3c05", + "contributors": [ + "bridge" + ] + }, + { + "path": "assets/shaders/viewport.wgsl", + "before_exists": true, + "before_bytes": 32685, + "before_sha256": "a4faec5492b81299bff8f88233962288130e82c05576af2d163379f37a4e83cd", + "candidate_bytes": 32892, + "candidate_sha256": "58049536e7688dd6b86f5a1a213c765934fff86c973ef32ebcbbd3ba6cad39b6", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/engine/src/cmd/render.rs", + "before_exists": true, + "before_bytes": 42766, + "before_sha256": "14f264d1539760050d594defb0cce0e563445f8a51d37893d76890c1bf2c863b", + "candidate_bytes": 44175, + "candidate_sha256": "13d0bc2e8a72589e0b7a6cad8a6d04d8a22d53196341be8ae6826afaf48584fa", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/engine/src/cmd/render/jobs.rs", + "before_exists": true, + "before_bytes": 66455, + "before_sha256": "9218559ff4fdb3ea1fd1cd1775e264f17bb074bf3870a3e50886b4790495c642", + "candidate_bytes": 79936, + "candidate_sha256": "925df1f1e39cfd201fb64fd165a89b399e6023d8e91e70e6085bbdf59256ddf1", + "contributors": [ + "recovery", + "raster", + "consumer" + ] + }, + { + "path": "crates/engine/src/render_jobs.rs", + "before_exists": true, + "before_bytes": 42380, + "before_sha256": "b189d8ffa378242431da15d964ec8ca417f7b6e172dbad1f50f65a9391175b19", + "candidate_bytes": 42460, + "candidate_sha256": "27aa67247bbd57610432caf62bfc51af25fcd51c8827c41df99f12bd1aa74666", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/gpu/src/path/denoise_tests.rs", + "before_exists": true, + "before_bytes": 15822, + "before_sha256": "2389b101e697f574fe5a2865aea61909ec66fb8b1a2f68544a398c3c93a8a362", + "candidate_bytes": 15894, + "candidate_sha256": "011bf8457c8fbfa4409ab5469d16472371112c9a68e1500d4d4c652e93f474e0", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/gpu/src/path/mod.rs", + "before_exists": true, + "before_bytes": 51620, + "before_sha256": "46c8338e2a3dece93875ee5b786ad580075f81e316eb8d6969ab0aa6be2d6795", + "candidate_bytes": 51630, + "candidate_sha256": "6fde27cacd9449468ace14cf56d1bf057030c741372a3b1498fefa7c23977d2c", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/gpu/src/path/tests.rs", + "before_exists": true, + "before_bytes": 164300, + "before_sha256": "34175a9ad6f72af3f21b36372105b9ccb0bd138a694cffb01b8a73a1a8567247", + "candidate_bytes": 164444, + "candidate_sha256": "206f281b911227041f1a9fdb882e6258f6ee2cd474eecb8437334c1712e3be2b", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/gpu/src/view.rs", + "before_exists": true, + "before_bytes": 270951, + "before_sha256": "b5f803507b6038801e8e19aa60fd031d4a2b13d40ddd269492c039482f48334b", + "candidate_bytes": 274678, + "candidate_sha256": "75b4b5ddb06f5ee520f04d0e7dc0640164571723be90668b606a879c9a10aae0", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/examples/cpu_resource_smoke.rs", + "before_exists": true, + "before_bytes": 8476, + "before_sha256": "bd888e7c19800bc1c732d98053ca258f87b12746d46ea101b250f7043c44793a", + "candidate_bytes": 8548, + "candidate_sha256": "962ec3c205a4a0203a2822654c3000493ce44ea19122b6dbe8be4c07fc28b6a1", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/host.rs", + "before_exists": true, + "before_bytes": 116953, + "before_sha256": "647c2d5d4453ee3028818f1088531b18aff17aa639168ac05c9d206028e86c78", + "candidate_bytes": 121712, + "candidate_sha256": "ce0e44ed698e90589ef2e0b55c80951d8ce021cf344ffe0c75c6f24479b503f6", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/job/host_regrade_tests.rs", + "before_exists": true, + "before_bytes": 7084, + "before_sha256": "4236fc7fd5e9e24418c00c93e31d84c6a136c898104e0aef7f214c7c376059f5", + "candidate_bytes": 7156, + "candidate_sha256": "f4bd4bd1216ff356691e99a911a110f43bde624cb4544281c9a521b27067d762", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/host_tests.rs", + "before_exists": true, + "before_bytes": 102170, + "before_sha256": "a421e66274f201634da648d7e4e5d2acd8ce96dc2c6096600f3f2f9dab9f0f4e", + "candidate_bytes": 106131, + "candidate_sha256": "538c64b36b4c4f34d602035337f93055cd944313acb8eb456c0769b84bc67be6", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/job/image.rs", + "before_exists": true, + "before_bytes": 36208, + "before_sha256": "64e0f44fe6665f94f8e7dd21e73e53c4fbfd58f06cb0f890482a1abb0cd9a5d0", + "candidate_bytes": 37010, + "candidate_sha256": "a747bad32db87152060bde4184c24a0612631a5a257818938f78ddc90f41bad9", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/image_tests.rs", + "before_exists": true, + "before_bytes": 30852, + "before_sha256": "3b209558bd7363fd41c039f034701141d30fe43ef3764a5cc42f48820bb44922", + "candidate_bytes": 43048, + "candidate_sha256": "79d3ca979647b93376058f8a477d188dc304b52f05ffec658df0cdfd30b12e68", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/led_strip/tests.rs", + "before_exists": true, + "before_bytes": 11730, + "before_sha256": "14e7c1042e25b360375908ee3602ca48b1d1df00bcf5099e49a0d51e29e07bd4", + "candidate_bytes": 11810, + "candidate_sha256": "8788bd088b5baab8a0ef6bd8026cf8d5c4eadfc53b8f3e1cf1ca32cc1b6fa828", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/mod.rs", + "before_exists": true, + "before_bytes": 70555, + "before_sha256": "fc57562478cd46620ee694b1d647d9ec6d7726ecf29b884df63de2738991098b", + "candidate_bytes": 81798, + "candidate_sha256": "ada28d60120f33fd41bef4bb310fe731f68db84f01304911fb072c71882602df", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/job/png.rs", + "before_exists": true, + "before_bytes": 7323, + "before_sha256": "b76bdbdde903711384a5235b8133520c05f10831e49fa3c204e36660b03342ad", + "candidate_bytes": 7403, + "candidate_sha256": "40abe173012f2be59f515517b3e89bbe530d2275f4d6f8b40cbd9686d76c84fd", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/raster_lights.rs", + "before_exists": true, + "before_bytes": 5463, + "before_sha256": "3ce43f30255b209dd9ad6bb36034f2678d7c0f03d7b6934ae4ba67dac908d63b", + "candidate_bytes": 9852, + "candidate_sha256": "8c2f13c31f4b0d9f0cfcf833bd3fc48edc2b1510a3d114237572c2b3c0243d2e", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/regrade.rs", + "before_exists": true, + "before_bytes": 9530, + "before_sha256": "6b38537e9296885277615e365f234177c4905d888e0c5fba77224955fc299fa2", + "candidate_bytes": 9698, + "candidate_sha256": "5a3d7e3079d5ba1c553b07f8f845876424d6488229baefbcbbc25048b5651a16", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/job/rt2_tests.rs", + "before_exists": true, + "before_bytes": 8639, + "before_sha256": "c68da6cf970df8cec8e850af62fc99580a5a1a073fc906564eaedfe8b76f9710", + "candidate_bytes": 12028, + "candidate_sha256": "92213bd6e991addbbea35c60f69fa205e5f5fe17f41b2bccc5f8c797c0fef5e3", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/anisotropic_faces_tests.rs", + "before_exists": true, + "before_bytes": 11436, + "before_sha256": "e33d50a81bd51f1afc5644fb4081611337d663c0fc790b8265839f59da307280", + "candidate_bytes": 11516, + "candidate_sha256": "b63e1d323aacc2eeea1056a332ada92df78a78ef52b8c2aee5313e064d8cc479", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/raytrace/anisotropic_reflection_image_tests.rs", + "before_exists": true, + "before_bytes": 13781, + "before_sha256": "cb237271c92c017d317a0e1e30f90510c23a5793b07d5eebe4c9ee3de53466c5", + "candidate_bytes": 13853, + "candidate_sha256": "8039e47fd0442f9620065ba180dbec7771bf4c0b606d12d66de3e5e63e1d0b52", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/raytrace/deterministic_primary_tests.rs", + "before_exists": true, + "before_bytes": 26110, + "before_sha256": "e963db2a2bcffb2917e7f76a28c3f079234d7f5849464576df0f19198727934d", + "candidate_bytes": 26657, + "candidate_sha256": "9de92d998490bcf542a7a29a1676dc9d32d920301609706b99f54e06c9e3157e", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/dielectric.rs", + "before_exists": true, + "before_bytes": 18121, + "before_sha256": "2063f440d7a9e495e0a0398ae9bb5084379731473f80d86ffb5be95f38dad0bc", + "candidate_bytes": 33896, + "candidate_sha256": "fbf044304e67b3156e4dd31c5b98585308773352c7565d7d8cce699dd232ffe7", + "contributors": [ + "foundation", + "owner", + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/dielectric_tests.rs", + "before_exists": true, + "before_bytes": 34116, + "before_sha256": "129ca64d6ba5df6bcb777814688a6334ed98c32e6068d4274312f3fdff045258", + "candidate_bytes": 56796, + "candidate_sha256": "bd61afc789288212971925f79a13b8623f7acb50e3ce936041985a4dc5fa54e5", + "contributors": [ + "foundation", + "owner", + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/environment_image_tests.rs", + "before_exists": true, + "before_bytes": 14556, + "before_sha256": "132605874c2006fdec090418bf54817d0991d8c91c8986952e8336253c11eb05", + "candidate_bytes": 14628, + "candidate_sha256": "9ee820799d6da59f8518197116984035d0292b86db4bbecb01135529590d1f53", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/raytrace/environment_reflection_tests.rs", + "before_exists": true, + "before_bytes": 12547, + "before_sha256": "a4434cf87fee71cb1d41d773fa1f1946065f7d019c7e6afabc0d917806ded988", + "candidate_bytes": 12619, + "candidate_sha256": "1466b408dd3e670ce05ae3cb0487e789c77a7079ad88093d83c70f4de4cb7d75", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/raytrace/image.rs", + "before_exists": true, + "before_bytes": 115405, + "before_sha256": "928115ae0c8cb460438da47a1b73c94f37e4a8dbf2c48c301957a40eadfb4ccf", + "candidate_bytes": 126109, + "candidate_sha256": "76ca3ec1dda4990921f1d72c240c6b130848d9b928ae5c37f8ce0203b914938e", + "contributors": [ + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/image_tests.rs", + "before_exists": true, + "before_bytes": 143136, + "before_sha256": "3e0f2c3f4b7b89bcfe521efc68571facf66a16334ff58812bf2fc7a0ec4a5bee", + "candidate_bytes": 171636, + "candidate_sha256": "97dc1ef0d2a8d7b38e584060678607718f27399dfd5c3e0fe6c9d6b9a97c835f", + "contributors": [ + "raster", + "consumer", + "Engineer-two-neutral-None-fillers" + ] + }, + { + "path": "crates/render/src/raytrace/lighting.rs", + "before_exists": true, + "before_bytes": 6620, + "before_sha256": "d4bc7940af35ced7a727106b371f67b53ec68615cbd3013de6ddcf5d42708486", + "candidate_bytes": 8678, + "candidate_sha256": "ab270656a20eedaea08e6858bdf0fd349ca64a5e528c0fc9162207adda541764", + "contributors": [ + "rgb" + ] + }, + { + "path": "crates/render/src/raytrace/lighting_tests.rs", + "before_exists": true, + "before_bytes": 8201, + "before_sha256": "2f7cdf2b371e7303cdbe91a5b064af0139db79acade2cf58581a30f424e0ca09", + "candidate_bytes": 14927, + "candidate_sha256": "cfd4194e7e5d6c6996700b0367984e2d91069078ee1a3aa3b6aa5453bd2cfc85", + "contributors": [ + "rgb" + ] + }, + { + "path": "crates/render/src/raytrace/primary_aa_tests.rs", + "before_exists": true, + "before_bytes": 89829, + "before_sha256": "e2af6353d85f56d4dc7d3d1dd838f7d2422db80fd256770e196b8d694158913c", + "candidate_bytes": 91606, + "candidate_sha256": "ec0fb1a530139202e419cfdeb0d577c11d5a660e0375bee3d73ffa7617c4e9cc", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/punctual_image_tests.rs", + "before_exists": true, + "before_bytes": 11192, + "before_sha256": "fbda59fd4a543f9fbdc450d4ec586db215cc69fe1a110a32d93d646ffc92d392", + "candidate_bytes": 11513, + "candidate_sha256": "fc07b7dbfb3996952d8c9ad55aa228a4bb4740ec5703bc6a5a551c7657f66394", + "contributors": [ + "raster", + "consumer" + ] + }, + { + "path": "crates/render/src/raytrace/reflection_image_tests.rs", + "before_exists": true, + "before_bytes": 15524, + "before_sha256": "4332edf40c81b6b9f57bd6a029eab7fb42aabcc371768874510eb44d156eb2f5", + "candidate_bytes": 15596, + "candidate_sha256": "87d80555bea2bf2e908f20223796f6d58d59508f13a930aa9e11eb36e6d999de", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/render/src/studio.rs", + "before_exists": true, + "before_bytes": 11054, + "before_sha256": "39eec7cc41207f966994b980a2cec11661a89f7e7a019608616f584261764d26", + "candidate_bytes": 29516, + "candidate_sha256": "c7b9ec18ab5c96a8b60c90c0a85ea9ed80d9702ad3a6a94d55a2765b85a34336", + "contributors": [ + "raster" + ] + }, + { + "path": "crates/ui-egui/src/render_workspace_library.rs", + "before_exists": true, + "before_bytes": 101279, + "before_sha256": "7c7131e8dca944e4088de6bb0865cb33ff481a3dff53f12e0e42f7727ca6ab6c", + "candidate_bytes": 102873, + "candidate_sha256": "e4b809875f965c6ae13b06931a3de8df7cbf654afc64fd2fed221cfcbd9ea762", + "contributors": [ + "bridge" + ] + }, + { + "path": "crates/ui-egui/src/render_workspace_materials.rs", + "before_exists": true, + "before_bytes": 48776, + "before_sha256": "5f9efcda8d42627eea7b05a8ccea2006a265492325824885442c76b6ec07e85a", + "candidate_bytes": 54225, + "candidate_sha256": "d0846cf8c8b0d2e05b7f8182cae26aae5ad1562c7d2e1b0561f6fcf9a39c80ef", + "contributors": [ + "bridge" + ] + }, + { + "path": "crates/ui-egui/src/render_workspace_tests.rs", + "before_exists": true, + "before_bytes": 592713, + "before_sha256": "8f2d6589162ad3d14b0aceb5a80fe0543738d7205ce2498ac0debc89b688ffd2", + "candidate_bytes": 607538, + "candidate_sha256": "844befc7fa329438cee00f86cd73ccab37e34336f015d0e7f0a8efd02aede4cb", + "contributors": [ + "raster", + "bridge" + ] + }, + { + "path": "crates/ui-egui/src/render_workspace_thumbnails.rs", + "before_exists": true, + "before_bytes": 7340, + "before_sha256": "ae0337f17a0348d10b181b2fad00170fbf6b8a8304a9dde764458b641306e0ea", + "candidate_bytes": 7420, + "candidate_sha256": "001729728a657f2ba0f2d1b50d1a4644f3f7ad505609cf8e674fa7f3f627e445", + "contributors": [ + "raster" + ] + }, + { + "path": "docs/render-cpu-progressive.md", + "before_exists": true, + "before_bytes": 9704, + "before_sha256": "0a2bc05d4751234afbab9002de42827807c48bbb71a254823ac31e38cd8fc373", + "candidate_bytes": 10324, + "candidate_sha256": "d5eb9a24058ae465529539768a3885cd14e38f2de14597e2eecb64ae5a099821", + "contributors": [ + "recovery" + ] + }, + { + "path": "docs/render-raytrace-dielectrics.md", + "before_exists": true, + "before_bytes": 10559, + "before_sha256": "b7cebd4e1472dfff08ebdb06345354dd285e8f39c02f9dac90cf3ecdd4914272", + "candidate_bytes": 11435, + "candidate_sha256": "a64ea715a470777ee2fb41c2ff52baccb942cf034b65c261c75389edbaf3acad", + "contributors": [ + "recovery" + ] + }, + { + "path": "tools/render-library/native_smoke.rs", + "before_exists": true, + "before_bytes": 6624, + "before_sha256": "2f51d83f9c5a68834b944d0c56a07365d9895d83ea52764bee43556e5f85a2e3", + "candidate_bytes": 6702, + "candidate_sha256": "ad399b42b79bfa14a419dd3bf3625f2cc6d4adb6667ffad34fb07b302341cf74", + "contributors": [ + "raster" + ] + } + ], + "original_private_aggregate_sha256": "ab52347ec85281dd61ddb6afe175a732a7f71a18e346d7b2a819365b7fff965a", + "public_patch_sha256": "66c6e428ec445a28593c31c4dfbb30a7a640e46e0780ea2491e47c125760d351", + "public_patch_only_representation_change": "The one truly absent locale file uses a /dev/null old header, replacing the private empty-placeholder header. All source/hunk bytes otherwise unchanged.", + "neutral_schema_rebind": { + "path": "crates/render/src/raytrace/image_tests.rs", + "function": "original_directional_fixture", + "before_sha256": "e3efdb2219a438950c4976bbc16bfbbdb73ed5b699d9f74490446ef5a52b926e", + "candidate_sha256": "97dc1ef0d2a8d7b38e584060678607718f27399dfd5c3e0fe6c9d6b9a97c835f", + "added_lines": [ + " raster_punctual_lights: None,", + " raster_area_lights: None," + ], + "original_donor_immutable": true, + "compiled": false, + "executed": false + }, + "new_declarations_UNRUN": 89, + "unit_declarations": [ + { + "unit": "recovery", + "before_test_declarations": 8, + "candidate_test_declarations": 8, + "new_declarations_UNRUN": 0 + }, + { + "unit": "foundation", + "before_test_declarations": 33, + "candidate_test_declarations": 45, + "new_declarations_UNRUN": 12 + }, + { + "unit": "owner", + "before_test_declarations": 45, + "candidate_test_declarations": 52, + "new_declarations_UNRUN": 7 + }, + { + "unit": "rgb", + "before_test_declarations": 8, + "candidate_test_declarations": 15, + "new_declarations_UNRUN": 7 + }, + { + "unit": "raster", + "before_test_declarations": 758, + "candidate_test_declarations": 795, + "new_declarations_UNRUN": 37 + }, + { + "unit": "bridge", + "before_test_declarations": 279, + "candidate_test_declarations": 289, + "new_declarations_UNRUN": 10 + }, + { + "unit": "consumer", + "before_test_declarations": 291, + "candidate_test_declarations": 307, + "new_declarations_UNRUN": 16 + } + ], + "source_reviews": { + "Root_composition": "d7b2ff11941d5f989ee207cdd65c50d639c687718b535775f4c22d542d3eb4af", + "consumer_API": "868a4a675bfa6beded9b8313566ac7fc97c23045143e4312c539b3846d9949ac", + "consumer_numeric": "8f880e53da1a3e194997f2f21498f22042677c87c6b260fbce8cef4643019882" + }, + "metadata_capture": { + "invocations": 1, + "argv": [ + "cargo", + "metadata", + "--format-version", + "1", + "--locked", + "--offline" + ], + "exit": 0, + "stderr_bytes": 0, + "source_unchanged": true, + "packages": 600, + "nodes": 600, + "workspace_members": 17, + "metadata_sha256": "7a2866dd0728c0081fd8a7fde32cb3232356ce761a4fc5c1ca485dd53de82489" + }, + "build_or_test_or_native_or_GPU_result": false, + "C21_failed_result_not_erased_or_transferred": true +}