9e6e0b8df1
* wip(render): reconcile completed material and image pipeline source with 0.20 (#5493)
Source-only integration reference for staged review, not a merge-ready aggregate.
Donor: 0xlillith/solidcraft@aea20b0115.
Upstream: 858e5995d6.
Retain original CPU/material contracts and explicit GPU donor provenance in
docs/render-materials-lab.md (#2067, #2191, #2780, #3306). Preserve released
format migrations and current navigation/startup/shell behavior. New saved
records use pending descriptors. The physical-card descriptor follows the
maintainer's material-engineering-cards naming request, with a legacy-lab
format-29 regression. Replace raw new panel hosts with shared containers.
Repository checks, complete workspace/all-target Clippy, and the independent
physical/resource authoring checks pass for this source. The fresh full local
CI invocation has reached test compilation and is not yet complete. Do not
transfer donor native output or prior test totals to this integration.
Generated review screenshots, video, package ZIP and machine logs remain at
the immutable personal evidence pin. Uncommitted geometric displacement is
backed up separately, not silently included. No kernel/vendor change, direct
main write, release or independent contributor-branch rewrite.
Co-authored-by: Christian Svensson <blue@cmd.nu>
* test(cli): pin the Compact camera-sample admission diagnostic (#5493)
The bounded request still refuses 1024x1024x64 samples before host initialization and writes no output. Update only the stale expected diagnostic to the existing Compact budget wording; production limits and code are unchanged. Exact-tree CLI regression suite: 14 passed, 0 failed. The full repository gate has been invoked separately and is not yet complete.
* Normalize UI container violation paths across platforms
Report repository-relative paths with forward slashes so diagnostics and the existing nested-package regression assertions agree on Windows and Unix. Keep the container detection rules unchanged.
Validation: official ui-containers gate and all seven focused xtask tests passed; rustfmt and diff checks passed. Only xtask/dependencies were compiled; no application build or heavy tests.
(cherry picked from commit 44b58d8e103a5fbc816ebf7c22b8de768ddf592b)
* fix(render): preserve camera contracts and correct acceptance regressions (#5493)
Preserve Design view.apply semantics with a separate strict Render camera command. Retain existing translations when English-only aliases collide; add material-axis entries and camera-specific pitch labels. Compare complete validated engineering cards and retain job handles before cancellation.
Focused and native acceptance is pinned to tree f8a423b21febd80ba88aaf1a67d5edbe2306314a. Full CI has been invoked separately and is not claimed green. Landing follows the render integration policy in #5493.
* fix(render): resolve showcase licence and upstream resource hygiene (#5493)
Record SychPL's explicit MIT OR Apache-2.0 grant, retaining source/model bytes and the Ubuntu lettering notice. Remove 80 absent attribution rows, personal fork records, dead delivery attributes and three fork/resource-only workflows. Existing xtask assets now performs bounded offline hash checks and rejects orphan render attribution; no parallel draft CI or package installation. Original authoring reproduction remains explicit. Scoped xtask tests, assets, Clippy, formatting and prepared SELENE validation pass; no application or renderer-wide result is inferred.
* fix(render): align saved bounds and progressive sample resolution (#5493)
Address review r4364211669/r4364211677/r4364211681/r4364211691/r4364211695. Persisted light/frame domains respect the existing 1e9 document bound; related LED/rectangle/direction cases use the same bound. Workstation primary resolve shares the 4096 admission cap and film counters use checked conversions. Exact candidate: 485 CPU render tests, 21 render document tests and strict scoped Clippy pass, including positive boundary round trips and 2048/4096 end-to-end checkpoints. No released format/migration edits, relaxed test limits or full-stack acceptance claim.
* wip(render): isolate optional resources and harden sample handling (#5493)
Review work in progress: opt-in encoded render library with reproducible runtime catalog exports; native-only robust dependency through the workspace; checked bloom slices; per-sample point-light diagnostics; independent area-light spatial/film keys. Resource-module binaries in both configurations, generation, Cargo production feature graphs and attribution checks pass. Full engine/render regression and combined acceptance are pending: do not merge this donor as a constituent or treat scoped resource proof as runtime acceptance.
* fix(gpu): preserve donor allocations through the scope-safety repair (#5722)
Port the native-validated #5723 scope-cleanup correction into the experimental donor, retaining its adaptive, volume, aging, photographic and bloom allocations. Same reverse-drain helper and regression cases; the donor combination still needs its own compile/test gate and is not covered retroactively by render-base results.
* claim: #1369
* Reject unknown pending concepts after format folding (#1369)
* test(render): close bounded sampling and bloom review regressions (#5493)
Validate the optional-resource/lighting/dependency donor at its exact tree. Required Vulkan GPU 127/0/3; CPU renderer 487/0; engine Render 72/0; document render 21/0; lean library 7/0; strict scoped Clippy, assets/layers/lists/containers and lean-engine WASM pass. Preserve original failed controller/typing attempts. This is the draft donor/disposition source, not a replacement for constituent render PRs or final main acceptance.
* wip(render): preserve stable aging target validation candidate
Exact staged source from prior review work on donor 3b892eab5e10f4508fa50f15b202630d5adfa594. This is a recovery/review checkpoint, NOT accepted delivery. An actual command-path regression currently fails because the selected executor refuses ordered surface aging. No assertion, capability or admission limit is weakened. Native/UI/full combination acceptance remains pending. Saved/runtime split adds one pending descriptor and retains original file scope; no main/render branch is changed.
* test(render): preserve numeric setup intent at the admitted coordinate bound
Follow up jyviko review on #5494 without weakening the corrected saved-coordinate contract. The positive clicked fixture uses 1e9 instead of inadmissible 2e9; explicit out-of-range cases still refuse, and the full saved setup round-trips through JSON and the native container. Exact-source Render workspace 95/0 and strict all-target UI Clippy pass. This does not incorporate the separately failing stable-aging candidate or claim full current-render acceptance.
* test(render): use the real GPU executor for saved aging
Move successful native cold-reopen Check/Start coverage from the CPU-backed protocol fixture into the production GPU executor tests. Verify capture-index changes preserve the stable target and that enabling aging changes both PNG and raw EXR output. Retain explicit, allocation-free refusal coverage for executors without aging support. Production capabilities and admission checks are unchanged.
* fix(render): persist stable identities for targeted aging (#5493)
Separate saved RenderBodyTarget identities from captured mesh ordinals. Reject legacy ambiguous targets, resolve Check/Start after visibility changes and preserve native reopening, copies and undo. Unsupported executors still refuse; real AMD Vulkan regression completes saved aging after reordered capture.
Source tree 6b84c8ad passes document 23, engine Render 75, GPU effects 5 and Render UI 95 with no failures; scoped strict Clippy, WASM and repository gates pass. Fresh CLI/native reopen and clean/aged GPU exports pass with identical physical totals and inspected actual images. Whole current-render integration is separate.
* fix(render): reconcile combined CPU/GPU contracts on current upstream
Unify captured resources/status and CPU-vs-GPU request schemas after the real two-parent integration; remove obsolete duplicate Vulkan selector and retain combined platform-filter regression. Deduplicate only identical or superseded test definitions, retaining the stronger card metadata and reserved-executor assertions. No assertions, admission limits or feature refusals are weakened.
All targets of render dependencies, GPU, engine, UI, CLI and native app pass cargo check with raytrace-cpu and bundled-render-library at tree c70d00d1. Native executable tests and full current-source acceptance remain pending. This is a private integration rehearsal for subsequent constituent PRs, not an aggregate official render/main merge.
* test(render): retain one complete host lifetime regression set
Deduplicate byte-identical DropProbe/task-lifetime tests and retain the adapted environment/texture ownership regressions with every assertion and complete memory estimate. Keep the registered-geometry admission regression once; only struct field order differed. Replace a one-element diagnostic loop with its equivalent block, preserving all wrap/width assertions.
Test-only integration repair. Formatting and diff checks pass; refreshed executable validation is required. No production behavior, limits, assertions or ignores changed.
* fix(doc): recognize the proven format-29 card descriptor alias
Normalize only the historical format-29 physical-material-cards spelling, and only when material-engineering-cards is registered. Admission and migration de-duplication use the same identity. Unknown concepts, wrong versions and incapable readers still refuse before mutation. Six controlled-history Rust regressions and actual CLI migration/no-clobber acceptance pass. No version, released migration or CI changes. Refs #5793, #1369, #5493.
* test(render): preserve grounding refusal before explicit instance moves
Update the two Render binding fixtures for upstream first-occurrence grounding. Verify grounded movement refuses without changing document/history, then explicitly unground through the public command before the intended move. Retain every target, resource, copy and persistence assertion. Refs #5493.
---------
Co-authored-by: Christian Svensson <blue@cmd.nu>
Co-authored-by: Victor Santos Oliveira <56417388+Vittuu@users.noreply.github.com>
Co-authored-by: cfaulkingham <colin.faulkingham@gmail.com>
516 lines
23 KiB
Rust
516 lines
23 KiB
Rust
use super::*;
|
|
use crate::{
|
|
ProductMesh,
|
|
job::{CancelToken, DielectricBoundary, ImageRequest, Integrator, RaytraceOptions, TaskPoll},
|
|
};
|
|
use solidcraft_geom::Mesh;
|
|
use std::sync::Arc;
|
|
|
|
pub(in crate::raytrace) fn box_body(thickness: f64) -> ProductMesh {
|
|
let positions = (0..8)
|
|
.map(|i| Vec3::new(if i & 1 == 0 { -10.0 } else { 10.0 }, if i & 2 == 0 { -10.0 } else { 10.0 }, if i & 4 == 0 { 0.0 } else { thickness }))
|
|
.collect();
|
|
let triangles =
|
|
vec![[0, 2, 3], [0, 3, 1], [4, 5, 7], [4, 7, 6], [0, 4, 6], [0, 6, 2], [1, 3, 7], [1, 7, 5], [0, 1, 5], [0, 5, 4], [2, 6, 7], [2, 7, 3]];
|
|
ProductMesh {
|
|
transmission: None,
|
|
name: "captured slab@occurrence-2".into(),
|
|
mesh: Arc::new(Mesh { positions, triangles, ..Default::default() }),
|
|
color: [255; 3],
|
|
opacity: 1.0,
|
|
surface: None,
|
|
faces: Vec::new(),
|
|
}
|
|
}
|
|
pub(in crate::raytrace) fn scene(body: ProductMesh) -> ProductScene {
|
|
let bounds = body.mesh.bounds();
|
|
ProductScene { meshes: vec![body], bounds }
|
|
}
|
|
pub(in crate::raytrace) fn input(boundary: DielectricBoundary) -> DielectricOptions {
|
|
DielectricOptions {
|
|
body_index: 0,
|
|
body_name: "captured slab@occurrence-2".into(),
|
|
boundary,
|
|
ior: 1.5,
|
|
absorption_per_mm: [0.0; 3],
|
|
thickness_mm: 0.0,
|
|
}
|
|
}
|
|
fn environment() -> Option<crate::job::RaytraceEnvironmentOptions> {
|
|
Some(crate::job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 })
|
|
}
|
|
pub(in crate::raytrace) fn request(options: RaytraceOptions) -> ImageRequest {
|
|
let mut camera = crate::Camera { distance: 50.0, ..Default::default() };
|
|
camera.set_view(crate::StandardView::Top);
|
|
ImageRequest {
|
|
environment: None,
|
|
textures: None,
|
|
integrator: Integrator::Raytrace,
|
|
raytrace: Some(options),
|
|
camera,
|
|
width: 1,
|
|
height: 1,
|
|
background: [255; 3],
|
|
transparent_background: false,
|
|
}
|
|
}
|
|
fn render(scene: ProductScene, options: RaytraceOptions) -> [u8; 4] {
|
|
let request = request(options.clone());
|
|
let mut task = super::super::image::ImageTask::new(scene, request, CancelToken::default(), options).unwrap();
|
|
for _ in 0..100_000 {
|
|
if let TaskPoll::Complete(png) = task.step(16384).unwrap() {
|
|
let image = ::image::load_from_memory(&png).unwrap().to_rgba8();
|
|
return image.get_pixel(0, 0).0;
|
|
}
|
|
}
|
|
panic!("bounded dielectric fixture failed to finish");
|
|
}
|
|
|
|
#[test]
|
|
fn normal_interface_has_four_percent_reflection() {
|
|
let hit = interface(-Vec3::Z, Vec3::Z, 1.0, 1.5).unwrap();
|
|
assert!((hit.reflectance - 0.04).abs() < 1e-14);
|
|
assert_eq!(hit.transmitted, Some(-Vec3::Z));
|
|
assert_eq!(hit.reflected, Vec3::Z);
|
|
}
|
|
|
|
#[test]
|
|
fn thirty_degree_snell_and_parallel_exit_are_reversible() {
|
|
let incident = Vec3::new(0.5, 0.0, -(3.0f64).sqrt() / 2.0);
|
|
let enter = interface(incident, Vec3::Z, 1.0, 1.5).unwrap();
|
|
let inside = enter.transmitted.unwrap();
|
|
assert!((inside.x - 1.0 / 3.0).abs() < 1e-14);
|
|
let exit = interface(inside, Vec3::Z, 1.5, 1.0).unwrap();
|
|
assert!((exit.transmitted.unwrap() - incident).len() < 1e-14);
|
|
assert!((exit.reflectance - enter.reflectance).abs() < 1e-14);
|
|
}
|
|
|
|
#[test]
|
|
fn internal_grazing_ray_is_totally_reflected() {
|
|
let hit = interface(Vec3::new(0.8, 0.0, -0.6), Vec3::Z, 1.5, 1.0).unwrap();
|
|
assert_eq!(hit.transmitted, None);
|
|
assert_eq!(hit.reflectance, 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn beer_lambert_uses_actual_millimetre_path() {
|
|
let a = attenuation([0.1, 0.2, 0.0], 2.0).unwrap();
|
|
let b = attenuation([0.1, 0.2, 0.0], 8.0).unwrap();
|
|
assert!((b.x - a.x.powi(4)).abs() < 1e-14);
|
|
assert!((b.y - a.y.powi(4)).abs() < 1e-14);
|
|
assert_eq!(b.z, 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn hostile_optics_are_refused() {
|
|
for v in [f64::NAN, f64::INFINITY, -1.0] {
|
|
assert!(interface(-Vec3::Z, Vec3::Z, v, 1.5).is_err());
|
|
assert!(attenuation([v, 0.0, 0.0], 1.0).is_err());
|
|
assert!(attenuation([0.0; 3], v).is_err());
|
|
}
|
|
assert!(interface(Vec3::Z, Vec3::Z, 1.0, 1.5).is_err());
|
|
assert_eq!(interface(Vec3::X, Vec3::Z, 1.0, 1.0).unwrap().reflectance, 0.0);
|
|
}
|
|
|
|
#[test]
|
|
fn closed_box_certification_requires_complete_outward_boundary() {
|
|
let original = box_body(2.0);
|
|
assert!(matches!(certify(&scene(original.clone()), &input(DielectricBoundary::ClosedBox)), Ok(Certificate::ClosedBox(_))));
|
|
let mut body = original.clone();
|
|
Arc::make_mut(&mut body.mesh).triangles.pop();
|
|
assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err());
|
|
let mut body = original.clone();
|
|
Arc::make_mut(&mut body.mesh).triangles[0].swap(0, 1);
|
|
assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err());
|
|
let mut body = original;
|
|
let mesh = Arc::make_mut(&mut body.mesh);
|
|
mesh.triangles[1] = mesh.triangles[0];
|
|
assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn captured_occurrence_identity_and_unsupported_boundary_are_refused() {
|
|
let scene = scene(box_body(2.0));
|
|
let mut material = input(DielectricBoundary::ClosedBox);
|
|
material.body_name = "captured slab@occurrence-1".into();
|
|
assert!(certify(&scene, &material).is_err());
|
|
material = input(DielectricBoundary::ThinSheet);
|
|
assert!(certify(&scene, &material).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn actual_png_closed_volume_absorption_uses_two_and_eight_mm() {
|
|
for thickness in [2.0, 8.0] {
|
|
let mut material = input(DielectricBoundary::ClosedBox);
|
|
material.ior = 1.0;
|
|
material.absorption_per_mm = [0.1, 0.0, 0.0];
|
|
let options = RaytraceOptions {
|
|
dielectrics: vec![material],
|
|
environment: environment(),
|
|
lights: Some(Vec::new()),
|
|
shadows: false,
|
|
..Default::default()
|
|
};
|
|
let actual = render(scene(box_body(thickness)), options);
|
|
let linear = Vec3::new((-0.1 * thickness).exp(), 1.0, 1.0);
|
|
let mapped = super::super::lighting::map_to_display(linear, 0.0).unwrap();
|
|
let encode = |v: f64| ((if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) * 255.0).round() as u8;
|
|
assert_eq!(actual, [encode(mapped.x), encode(mapped.y), encode(mapped.z), 255]);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn actual_png_clear_volume_includes_multiple_fresnel_branches() {
|
|
let options = RaytraceOptions {
|
|
dielectrics: vec![input(DielectricBoundary::ClosedBox)],
|
|
environment: environment(),
|
|
lights: Some(Vec::new()),
|
|
shadows: false,
|
|
..Default::default()
|
|
};
|
|
let actual = render(scene(box_body(2.0)), options);
|
|
// Constant unit environment, no absorption: all branches sum to almost one.
|
|
// Eight boundaries drop only a very small unresolved Fresnel tail.
|
|
assert_eq!(actual, [188, 188, 188, 255]);
|
|
}
|
|
|
|
#[test]
|
|
fn overlapping_volumes_are_refused_before_pixel_work() {
|
|
let mut scene = scene(box_body(2.0));
|
|
scene.meshes.push(box_body(2.0));
|
|
let first = input(DielectricBoundary::ClosedBox);
|
|
let mut second = first.clone();
|
|
second.body_index = 1;
|
|
let options = RaytraceOptions { dielectrics: vec![first, second], ..Default::default() };
|
|
assert!(super::super::image::admit(&scene, &request(options.clone()), &options).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn cancelled_dielectric_job_cannot_publish_png() {
|
|
let options = RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox)], ..Default::default() };
|
|
let cancel = CancelToken::default();
|
|
let mut task = super::super::image::ImageTask::new(scene(box_body(2.0)), request(options.clone()), cancel.clone(), options).unwrap();
|
|
task.step(1).unwrap();
|
|
cancel.cancel();
|
|
assert_eq!(task.step(1).err().unwrap().code, crate::job::ErrorCode::Cancelled);
|
|
}
|
|
|
|
#[test]
|
|
fn runtime_dielectric_inputs_are_bounded_and_default_off() {
|
|
assert!(RaytraceOptions::default().dielectrics.is_empty());
|
|
let options = RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox); 9], ..Default::default() };
|
|
assert!(options.validate().is_err());
|
|
let mut material = input(DielectricBoundary::ClosedBox);
|
|
material.thickness_mm = 1.0;
|
|
let options = RaytraceOptions { dielectrics: vec![material], ..Default::default() };
|
|
assert!(options.validate().is_err());
|
|
let oversized = serde_json::json!({"dielectrics": vec![input(DielectricBoundary::ThinSheet);9]});
|
|
assert!(serde_json::from_value::<RaytraceOptions>(oversized).is_err());
|
|
assert!(serde_json::from_value::<RaytraceOptions>(serde_json::json!({"dielectrics":[{"body_index":0,"body_name":"x".repeat(1025),"boundary":"closed_box","ior":1.5,"absorption_per_mm":[0,0,0],"thickness_mm":0}]})).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn oblique_parallel_slab_offset_scales_with_actual_thickness() {
|
|
let direction = Vec3::new(0.5, 0.0, -(3.0f64).sqrt() / 2.0);
|
|
let inside = interface(direction, Vec3::Z, 1.0, 1.5).unwrap().transmitted.unwrap();
|
|
let mut offsets = Vec::new();
|
|
for thickness in [2.0, 8.0] {
|
|
let bottom = Triangle::new([Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(10.0, -10.0, 0.0)]).unwrap();
|
|
let ray = super::super::Ray::new(Vec3::new(0.0, 0.0, thickness), inside, 0.0, 100.0).unwrap();
|
|
let hit = bottom.intersect(&ray).unwrap();
|
|
let exit = ray.at(hit.distance).unwrap();
|
|
assert!((hit.distance - thickness / -inside.z).abs() < 1e-13);
|
|
let undeviated_x = thickness * direction.x / -direction.z;
|
|
offsets.push(undeviated_x - exit.x);
|
|
}
|
|
assert!((offsets[1] - 4.0 * offsets[0]).abs() < 1e-13);
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_is_certified_separately_and_duplicate_faces_refuse() {
|
|
let mut body = box_body(2.0);
|
|
Arc::make_mut(&mut body.mesh).triangles = vec![[4, 5, 7], [4, 7, 6]];
|
|
let mut material = input(DielectricBoundary::ThinSheet);
|
|
material.ior = 1.0;
|
|
material.thickness_mm = 8.0;
|
|
material.absorption_per_mm = [0.1, 0.0, 0.0];
|
|
assert!(matches!(certify(&scene(body.clone()), &material), Ok(Certificate::ThinSheet)));
|
|
let options =
|
|
RaytraceOptions { dielectrics: vec![material], environment: environment(), lights: Some(Vec::new()), shadows: false, ..Default::default() };
|
|
let actual = render(scene(body.clone()), options);
|
|
let closed = RaytraceOptions {
|
|
environment: environment(),
|
|
dielectrics: vec![DielectricOptions { ior: 1.0, absorption_per_mm: [0.1, 0.0, 0.0], ..input(DielectricBoundary::ClosedBox) }],
|
|
lights: Some(Vec::new()),
|
|
shadows: false,
|
|
..Default::default()
|
|
};
|
|
assert_eq!(actual, render(scene(box_body(8.0)), closed));
|
|
let mesh = Arc::make_mut(&mut body.mesh);
|
|
mesh.triangles[1] = mesh.triangles[0];
|
|
assert!(certify(&scene(body), &input(DielectricBoundary::ThinSheet)).is_err());
|
|
}
|
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
#[test]
|
|
fn native_dielectric_job_uses_existing_host_and_retained_png_lease() {
|
|
use crate::job::{CpuHost, JobId, Phase};
|
|
let host = CpuHost::for_platform().unwrap();
|
|
let options = RaytraceOptions {
|
|
dielectrics: vec![input(DielectricBoundary::ClosedBox)],
|
|
environment: environment(),
|
|
lights: Some(Vec::new()),
|
|
shadows: false,
|
|
..Default::default()
|
|
};
|
|
let scene = scene(box_body(2.0));
|
|
let weak = Arc::downgrade(&scene.meshes[0].mesh);
|
|
let id = JobId { session: 1655, serial: 1, generation: 1 };
|
|
let handle = host.submit(id, 1, scene, request(options)).unwrap();
|
|
assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed);
|
|
let frame = handle.frame().unwrap().unwrap();
|
|
assert!(::image::load_from_memory(frame.png()).is_ok());
|
|
assert!(weak.upgrade().is_none());
|
|
assert!(host.admitted_bytes() > 0);
|
|
drop(handle);
|
|
assert!(host.admitted_bytes() > 0);
|
|
drop(frame);
|
|
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
|
|
while host.admitted_bytes() != 0 {
|
|
assert!(std::time::Instant::now() < deadline, "worker did not release terminal request record");
|
|
std::thread::yield_now();
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn secondary_environment_is_explicit_and_primary_background_remains_display_srgb() {
|
|
let options =
|
|
RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox)], lights: Some(Vec::new()), shadows: false, ..Default::default() };
|
|
assert_eq!(render(scene(box_body(2.0)), options.clone()), [0, 0, 0, 255]);
|
|
let mut request = request(options.clone());
|
|
request.camera.target.x = 50.0;
|
|
request.background = [20, 30, 40];
|
|
request.raytrace.as_mut().unwrap().exposure_ev = 4.0;
|
|
let options = request.raytrace.clone().unwrap();
|
|
let mut task = super::super::image::ImageTask::new(scene(box_body(2.0)), request, CancelToken::default(), options).unwrap();
|
|
for _ in 0..100_000 {
|
|
if let TaskPoll::Complete(png) = task.step(16384).unwrap() {
|
|
assert_eq!(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0, [20, 30, 40, 255]);
|
|
return;
|
|
}
|
|
}
|
|
panic!("primary background fixture failed to finish");
|
|
}
|
|
|
|
#[test]
|
|
fn typed_runtime_roundtrip_preserves_default_empty_and_explicit_lists() {
|
|
for options in [
|
|
RaytraceOptions::default(),
|
|
RaytraceOptions { lights: Some(Vec::new()), ..Default::default() },
|
|
RaytraceOptions { dielectrics: vec![input(DielectricBoundary::ClosedBox)], environment: environment(), ..Default::default() },
|
|
] {
|
|
let encoded = serde_json::to_value(&options).unwrap();
|
|
let decoded: RaytraceOptions = serde_json::from_value(encoded).unwrap();
|
|
assert_eq!(decoded, options);
|
|
assert!(decoded.validate().is_ok());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn actual_oblique_png_selects_the_snell_shifted_colour_target() {
|
|
fn target(name: &str, y0: f64, y1: f64, color: Vec3) -> ProductMesh {
|
|
ProductMesh {
|
|
transmission: None,
|
|
name: name.into(),
|
|
mesh: Arc::new(Mesh {
|
|
positions: vec![Vec3::new(-20.0, y0, -1.0), Vec3::new(20.0, y0, -1.0), Vec3::new(20.0, y1, -1.0), Vec3::new(-20.0, y1, -1.0)],
|
|
normals: vec![Vec3::Z; 4],
|
|
triangles: vec![[0, 1, 2], [0, 2, 3]],
|
|
..Default::default()
|
|
}),
|
|
color: [255; 3],
|
|
opacity: 1.0,
|
|
surface: Some(crate::surface::OpaqueSurface::new(color, 0.0, 1.0, 1.0).unwrap()),
|
|
faces: Vec::new(),
|
|
}
|
|
}
|
|
let mut scene = scene(box_body(8.0));
|
|
scene.meshes.push(target("near blue stripe", -20.0, 4.0, Vec3::Z));
|
|
scene.meshes.push(target("far red stripe", 4.0, 20.0, Vec3::X));
|
|
for body in &scene.meshes {
|
|
scene.bounds = scene.bounds.union(&body.mesh.bounds());
|
|
}
|
|
// Entry at (0,0,8), incidence30deg. Independent Snell values give
|
|
// y=8/sqrt(8)+1/sqrt(3)=3.4058 for glass and 9/sqrt(3)=5.1962
|
|
// for index-matched air at target z=-1, on opposite sides of y=4.
|
|
let shifted_y = 8.0 / 8.0f64.sqrt() + 1.0 / 3.0f64.sqrt();
|
|
let straight_y = 9.0 / 3.0f64.sqrt();
|
|
assert!(shifted_y < 4.0 && straight_y > 4.0);
|
|
let mut results = Vec::new();
|
|
for ior in [1.5, 1.0] {
|
|
let options = RaytraceOptions {
|
|
dielectrics: vec![DielectricOptions { ior, ..input(DielectricBoundary::ClosedBox) }],
|
|
lights: Some(vec![crate::job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 4.0 }]),
|
|
shadows: false,
|
|
..Default::default()
|
|
};
|
|
let mut request = request(options.clone());
|
|
request.camera.yaw = 0.0;
|
|
request.camera.pitch = std::f64::consts::PI / 3.0;
|
|
request.camera.target = Vec3::new(0.0, 0.0, 8.0);
|
|
let mut task = super::super::image::ImageTask::new(scene.clone(), request, CancelToken::default(), options).unwrap();
|
|
let mut pixel = None;
|
|
for _ in 0..100_000 {
|
|
if let TaskPoll::Complete(png) = task.step(16384).unwrap() {
|
|
pixel = Some(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0);
|
|
break;
|
|
}
|
|
}
|
|
results.push(pixel.expect("oblique slab fixture must finish"));
|
|
}
|
|
let glass = results[0];
|
|
let matched = results[1];
|
|
assert!(u16::from(glass[2]) > u16::from(glass[0]) + 50, "glass ray missed the predicted blue stripe: {glass:?}");
|
|
assert!(u16::from(matched[0]) > u16::from(matched[2]) + 50, "index-matched ray missed the predicted red stripe: {matched:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_brewster_sums_polarizations_before_averaging() {
|
|
// tan(theta_B) = 3/2, so single-interface Rs = 25/169 and Rp = 0.
|
|
// The lossless slab returns Rs/(1+Rs) after the unpolarized average.
|
|
let direction = Vec3::new(3.0, 0.0, -2.0) / 13.0f64.sqrt();
|
|
let material = input(DielectricBoundary::ThinSheet);
|
|
let (_, polarized) = polarized_interface(direction, Vec3::Z, 1.0, 1.5).unwrap();
|
|
assert!((polarized[0] - 25.0 / 169.0).abs() < 1e-14);
|
|
assert!(polarized[1].abs() < 1e-28);
|
|
let (optics, reflected, transmitted) = thin_sheet(direction, Vec3::Z, &material).unwrap();
|
|
let expected_r = 25.0 / 194.0;
|
|
let expected_t = 169.0 / 194.0;
|
|
assert!((reflected - Vec3::new(expected_r, expected_r, expected_r)).len() < 1e-14);
|
|
assert!((transmitted - Vec3::new(expected_t, expected_t, expected_t)).len() < 1e-14);
|
|
assert!((optics.transmitted.unwrap() - direction).len() < 1e-14);
|
|
// The old average-before-series result differs by this exact rational.
|
|
assert!((50.0 / 363.0 - reflected.x - 625.0 / 70422.0).abs() < 1e-14);
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_normal_incidence_keeps_the_lossless_slab_limit() {
|
|
let material = input(DielectricBoundary::ThinSheet);
|
|
let (_, reflected, transmitted) = thin_sheet(-Vec3::Z, Vec3::Z, &material).unwrap();
|
|
// Rs = Rp = 1/25: the two-interface lossless slab has R = 1/13.
|
|
let r = 1.0 / 13.0;
|
|
let t = 12.0 / 13.0;
|
|
assert!((reflected - Vec3::new(r, r, r)).len() < 1e-14);
|
|
assert!((transmitted - Vec3::new(t, t, t)).len() < 1e-14);
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_matched_indices_keep_beer_lambert_transmission() {
|
|
let material = DielectricOptions {
|
|
ior: 1.0,
|
|
thickness_mm: 2.0,
|
|
absorption_per_mm: [2.0f64.ln() / 2.0, 4.0f64.ln() / 2.0, 0.0],
|
|
..input(DielectricBoundary::ThinSheet)
|
|
};
|
|
let (optics, reflected, transmitted) = thin_sheet(-Vec3::Z, Vec3::Z, &material).unwrap();
|
|
assert_eq!(reflected, Vec3::ZERO);
|
|
assert!((transmitted - Vec3::new(0.5, 0.25, 1.0)).len() < 1e-14);
|
|
assert_eq!(optics.transmitted, Some(-Vec3::Z));
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_zero_thickness_index_matched_grazing_is_transparent() {
|
|
// Equal indices remove the interface; zero thickness means exp(-sigma * 0) = 1.
|
|
for absorption_per_mm in [[0.0; 3], [100.0, 0.25, 1.0]] {
|
|
let material = DielectricOptions { ior: 1.0, absorption_per_mm, ..input(DielectricBoundary::ThinSheet) };
|
|
let (optics, reflected, transmitted) = thin_sheet(Vec3::X, Vec3::Z, &material).unwrap();
|
|
assert_eq!(optics.reflectance, 0.0);
|
|
assert_eq!(optics.transmitted, Some(Vec3::X));
|
|
assert_eq!(reflected, Vec3::ZERO);
|
|
assert_eq!(transmitted, Vec3::new(1.0, 1.0, 1.0));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_positive_thickness_index_matched_grazing_refuses_without_tir() {
|
|
let material = DielectricOptions { ior: 1.0, thickness_mm: 1.0, ..input(DielectricBoundary::ThinSheet) };
|
|
let optics = interface(Vec3::X, Vec3::Z, 1.0, 1.0).unwrap();
|
|
assert_eq!(optics.transmitted, Some(Vec3::X));
|
|
assert_eq!(optics.reflectance, 0.0);
|
|
assert!(matches!(thin_sheet(Vec3::X, Vec3::Z, &material), Err(TraceError::InvalidInput("grazing sheet thickness is unsupported"))));
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_zero_thickness_grazing_still_validates_absorption() {
|
|
for sigma in [f64::NAN, f64::INFINITY, -1.0, 101.0] {
|
|
let material = DielectricOptions { ior: 1.0, absorption_per_mm: [sigma, 0.0, 0.0], ..input(DielectricBoundary::ThinSheet) };
|
|
assert!(matches!(thin_sheet(Vec3::X, Vec3::Z, &material), Err(TraceError::InvalidInput("dielectric absorption or distance"))));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn thin_sheet_absorbing_brewster_keeps_separate_internal_returns() {
|
|
let direction = Vec3::new(3.0, 0.0, -2.0) / 13.0f64.sqrt();
|
|
let material = DielectricOptions {
|
|
// cos(theta_t) = 3/sqrt(13), hence the one-pass distance is 1 mm.
|
|
thickness_mm: 3.0 / 13.0f64.sqrt(),
|
|
absorption_per_mm: [2.0f64.ln(), 2.0f64.ln(), 0.0],
|
|
..input(DielectricBoundary::ThinSheet)
|
|
};
|
|
let (_, reflected, transmitted) = thin_sheet(direction, Vec3::Z, &material).unwrap();
|
|
// Independent rational series with Rs = 25/169, Rp = 0, a = 1/2.
|
|
let r = 6625.0 / 75746.0;
|
|
let t = 65521.0 / 151492.0;
|
|
assert!((reflected - Vec3::new(r, r, 25.0 / 194.0)).len() < 1e-14);
|
|
assert!((transmitted - Vec3::new(t, t, 169.0 / 194.0)).len() < 1e-14);
|
|
assert!(reflected.x + transmitted.x < 1.0);
|
|
}
|
|
|
|
#[test]
|
|
fn actual_png_brewster_thin_sheet_matches_reflected_energy() {
|
|
let mut sheet = box_body(2.0);
|
|
Arc::make_mut(&mut sheet.mesh).triangles.retain(|t| *t == [4, 5, 7] || *t == [4, 7, 6]);
|
|
let mut scene = scene(sheet);
|
|
let absorber = ProductMesh {
|
|
transmission: None,
|
|
name: "unlit opaque transmission target".into(),
|
|
mesh: Arc::new(Mesh {
|
|
positions: vec![Vec3::new(-20.0, -20.0, -1.0), Vec3::new(20.0, -20.0, -1.0), Vec3::new(20.0, 20.0, -1.0), Vec3::new(-20.0, 20.0, -1.0)],
|
|
normals: vec![Vec3::Z; 4],
|
|
triangles: vec![[0, 1, 2], [0, 2, 3]],
|
|
..Default::default()
|
|
}),
|
|
color: [0; 3],
|
|
opacity: 1.0,
|
|
surface: None,
|
|
faces: Vec::new(),
|
|
};
|
|
scene.bounds = scene.bounds.union(&absorber.mesh.bounds());
|
|
scene.meshes.push(absorber);
|
|
let options = RaytraceOptions {
|
|
dielectrics: vec![input(DielectricBoundary::ThinSheet)],
|
|
environment: environment(),
|
|
lights: Some(Vec::new()),
|
|
shadows: false,
|
|
..Default::default()
|
|
};
|
|
let mut request = request(options.clone());
|
|
request.camera.yaw = 0.0;
|
|
request.camera.pitch = (2.0f64 / 3.0).atan();
|
|
request.camera.target = Vec3::new(0.0, 0.0, 2.0);
|
|
let (_, direction) = request.camera.ray(0.5, 0.5, 1.0, 1.0);
|
|
assert!((-direction.z - 2.0 / 13.0f64.sqrt()).abs() < 1e-14);
|
|
let mut task = super::super::image::ImageTask::new(scene, request, CancelToken::default(), options).unwrap();
|
|
let mut pixel = None;
|
|
for _ in 0..100_000 {
|
|
if let TaskPoll::Complete(png) = task.step(16384).unwrap() {
|
|
pixel = Some(::image::load_from_memory(&png).unwrap().to_rgba8().get_pixel(0, 0).0);
|
|
break;
|
|
}
|
|
}
|
|
// Only the reflected branch sees the unit white environment. R = 25/194
|
|
// maps through Reinhard to 25/219, then sRGB to 95. The old R = 50/363
|
|
// maps to 98, so this also detects a consumer still using the old series.
|
|
assert_eq!(pixel.expect("Brewster sheet fixture must finish"), [95, 95, 95, 255]);
|
|
}
|