Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

render: add CPU and GPU rough Glass, films, dispersion and caustics (#12200)

selune3a70b437089b
diff --git a/assets/locales/ar.json b/assets/locales/ar.json
index 4fda4f11b6..52853d6e0b 100644
--- a/assets/locales/ar.json
+++ b/assets/locales/ar.json
@@ -3191,7 +3191,7 @@
"render.category_wood": "خشب",
"render.check_glass_cpu": "يدعم CPU صفائح زجاج مستوية وصناديق محاذية للمحاور بعد التحقق منها. تتطلب الشبكات المغلقة العامة والتعشيق والتشتت الداخلي إضاءة غير مباشرة. لا تزال الظلال النافذة عبر الزجاج المغلق غير مدعومة.",
"render.check_glass_gpu": "يدعم GPU أوساط زجاج منفصلة متحققًا منها، أو تعشيقًا متحققًا منه عند تفعيله صراحةً. يتطلب التعشيق أغلفة خارجية محدبة وأجسامًا داخلية محتواة بالكامل وحدودًا غير متلامسة.",
- "render.check_media_remaining": "لا تزال تأثيرات الزجاج الخشن وشبكات الكثافة والإزاحة والنقل الطيفي غير متاحة.",
+ "render.check_media_remaining": "لا تزال شبكات الكثافة والإزاحة والتكامل الطيفي الكامل ونقل حالة الاستقطاب غير متاحة.",
"render.check_media_scope": "يتطلب التشتت الداخلي النشط وسطًا زجاجيًا مغلقًا مع إيقاف نفاذ أشعة الظل المستقيمة وإزالة الضجيج. ويتطلب GPU أيضًا طبقة عينات فرينل واحدة. لا يمكن جمع الغلاف الجوي الخارجي النشط مع الزجاج أو إزالة ضجيج الأسطح.",
"render.check_opaque": "الشفافية: أسطح معتمة فقط؛ ألفا الخلفية مدعومة.",
"render.check_sorted_alpha": "الشفافية: تقريب ألفا مرتّب.",
diff --git a/assets/locales/de.json b/assets/locales/de.json
index 80db7e4d47..c25d206bf1 100644
--- a/assets/locales/de.json
+++ b/assets/locales/de.json
@@ -2945,7 +2945,7 @@
"render.category_wood": "Holz",
"render.check_glass_cpu": "Die CPU unterstützt geprüfte ebene Glasscheiben und achsenparallele Boxen. Allgemeine geschlossene Netze, Verschachtelung und innere Streuung erfordern indirekte Beleuchtung. Durch geschlossenes Glas übertragene Schatten bleiben nicht unterstützt.",
"render.check_glass_gpu": "Die GPU unterstützt geprüfte getrennte Glasmedien oder ausdrücklich aktivierte geprüfte Verschachtelung. Dafür müssen die äußeren Körper konvex und die inneren streng enthalten sein; Grenzen dürfen sich nicht berühren.",
- "render.check_media_remaining": "Raues Glas, Dichtegitter, Displacement und spektraler Lichttransport bleiben nicht verfügbar.",
+ "render.check_media_remaining": "Dichtegitter, Displacement, vollständige spektrale Integration und fortgeführte Polarisation bleiben nicht verfügbar.",
"render.check_media_scope": "Aktive innere Streuung benötigt ein geschlossenes Glasmedium ohne gerade Schattenübertragung und ohne Rauschreduzierung. Die GPU benötigt außerdem eine Fresnel-Schicht. Aktive äußere Atmosphäre kann nicht mit Glas oder Oberflächen-Rauschreduzierung kombiniert werden.",
"render.check_opaque": "Transparenz: nur undurchsichtige Oberflächen; Hintergrund-Alpha wird unterstützt.",
"render.check_sorted_alpha": "Transparenz: Näherung mit sortiertem Alpha.",
diff --git a/assets/locales/en-GB.json b/assets/locales/en-GB.json
index ad01d9c25e..0c1241aea4 100644
--- a/assets/locales/en-GB.json
+++ b/assets/locales/en-GB.json
@@ -160,6 +160,7 @@
"render.background_workflow": "Choose the background you intend: a camera-only colour/gradient, a physical stage that receives light, or HDR illumination. They are independent. Live Preview is a modelling view; render a new image or regrade a retained master to see camera finishing.",
"render.base_color": "Base colour · sRGB",
"render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalised box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.",
+ "render.check_media_remaining": "Density grids, displacement, full spectral integration and propagated polarisation remain unavailable.",
"render.chromatic_offset": "Chromatic edge offset",
"render.cpu_area_editor_help": "Full side vectors in millimeters; U cross V points towards the emitting side. This differs from GPU half-edge vectors.",
"render.cpu_light_help": "Up to eight directional lights. An empty custom list turns them off; selecting a preset restores its lights. Colours are linear RGB and intensity is relative, not watts.",
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 775c875860..b0a7cdfa01 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -3191,7 +3191,7 @@
"render.category_wood": "Wood",
"render.check_glass_cpu": "CPU supports certified planar Glass sheets and axis-aligned boxes. General closed meshes, nesting and interior scattering require Indirect lighting. Closed transmitted shadows remain unsupported.",
"render.check_glass_gpu": "GPU supports certified disjoint Glass or explicit certified nesting. Nesting requires convex parents, strictly contained children and no touching boundaries.",
- "render.check_media_remaining": "Rough Glass, density grids, displacement and spectral transport remain unavailable.",
+ "render.check_media_remaining": "Density grids, displacement, full spectral integration and propagated polarization remain unavailable.",
"render.check_media_scope": "Active interior scattering needs a closed Glass medium, straight shadow transmission off and Denoise off. GPU also needs one Fresnel stratum. Active exterior Atmosphere cannot combine with Glass or surface Denoise.",
"render.check_opaque": "Transparency: opaque surfaces only; background alpha is supported.",
"render.check_sorted_alpha": "Transparency: sorted alpha approximation.",
diff --git a/assets/locales/he.json b/assets/locales/he.json
index 0074329c32..0a4a15ef9e 100644
--- a/assets/locales/he.json
+++ b/assets/locales/he.json
@@ -3191,7 +3191,7 @@
"render.category_wood": "עץ",
"render.check_glass_cpu": "ה־CPU תומך בלוחות זכוכית מישוריים ובתיבות מקבילות לצירים שעברו אימות. רשתות סגורות כלליות, קינון ופיזור פנימי דורשים תאורה עקיפה. העברת צל דרך זכוכית סגורה עדיין אינה נתמכת.",
"render.check_glass_gpu": "ה־GPU תומך בנפחי זכוכית נפרדים שעברו אימות או בקינון מאומת שמופעל במפורש. קינון דורש גופים חיצוניים קמורים, גופים פנימיים המוכלים בתוכם ממש וגבולות שאינם נוגעים זה בזה.",
- "render.check_media_remaining": "זכוכית מחוספסת, רשתות צפיפות, הסטת משטח והעברת אור ספקטרלית עדיין אינן זמינות.",
+ "render.check_media_remaining": "רשתות צפיפות, הסטת משטח, אינטגרציה ספקטרלית מלאה והעברת מצב קיטוב עדיין אינן זמינות.",
"render.check_media_scope": "פיזור פנימי פעיל דורש נפח זכוכית סגור, העברת קרני צל ישרות כבויה והסרת רעש כבויה. ה־GPU דורש גם שכבת פרנל אחת. אי אפשר לשלב אטמוספירה חיצונית פעילה עם זכוכית או עם הסרת רעש משטחית.",
"render.check_opaque": "שקיפות: משטחים אטומים בלבד; אלפא של הרקע נתמכת.",
"render.check_sorted_alpha": "שקיפות: קירוב אלפא ממוין.",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 0bb345e852..342080dea3 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -3191,7 +3191,7 @@
"render.category_wood": "木材",
"render.check_glass_cpu": "CPUは検証済みの平面ガラス薄板と軸に平行な箱に対応します。一般の閉じたメッシュ、入れ子、内部散乱には間接照明が必要です。閉じたガラスを通る透過影には未対応です。",
"render.check_glass_gpu": "GPUは検証済みの分離したガラス、または明示的に有効にした検証済みの入れ子に対応します。入れ子には凸形状の親、厳密に内包された子、接触しない境界が必要です。",
- "render.check_media_remaining": "粗いガラス、密度グリッド、ディスプレイスメント、分光輸送には未対応です。",
+ "render.check_media_remaining": "密度グリッド、変位、完全なスペクトル積分、偏光状態の伝播は未対応です。",
"render.check_media_scope": "有効な内部散乱には閉じたガラス媒質を使い、直線の影透過とノイズ除去をオフにします。GPUではフレネル層を1つにします。有効な外部の大気はガラスや表面ノイズ除去と併用できません。",
"render.check_opaque": "透明度:不透明サーフェスのみ。背景アルファに対応。",
"render.check_sorted_alpha": "透明度:ソート済みアルファによる近似。",
diff --git a/assets/locales/ko.json b/assets/locales/ko.json
index 9a6336f840..b93f362527 100644
--- a/assets/locales/ko.json
+++ b/assets/locales/ko.json
@@ -2470,7 +2470,7 @@
"render.category_wood": "목재",
"render.check_glass_cpu": "CPU는 검증된 평면 유리판과 축 정렬 상자를 지원합니다. 일반적인 닫힌 메시, 중첩 및 내부 산란에는 간접광이 필요합니다. 닫힌 유리를 통과하는 투과 그림자는 아직 지원하지 않습니다.",
"render.check_glass_gpu": "GPU는 검증된 분리 유리 또는 명시적으로 활성화한 검증된 중첩을 지원합니다. 중첩에는 볼록한 바깥 형상, 완전히 내부에 포함된 안쪽 형상 및 서로 닿지 않는 경계가 필요합니다.",
- "render.check_media_remaining": "거친 유리, 밀도 격자, 디스플레이스먼트 및 분광 광전달은 아직 지원하지 않습니다.",
+ "render.check_media_remaining": "밀도 격자, 변위, 전체 스펙트럼 적분 및 편광 상태 전파는 지원되지 않습니다.",
"render.check_media_scope": "활성 내부 산란에는 닫힌 유리 매질이 필요하며 직선 그림자 투과와 노이즈 제거를 꺼야 합니다. GPU에는 프레넬 계층도 하나만 필요합니다. 활성 외부 대기는 유리 또는 표면 노이즈 제거와 함께 사용할 수 없습니다.",
"render.check_opaque": "투명도: 불투명 표면만 지원하며 배경 알파를 지원합니다.",
"render.check_sorted_alpha": "투명도: 정렬된 알파 근사.",
diff --git a/assets/locales/pending/glass-material-models.json b/assets/locales/pending/glass-material-models.json
new file mode 100644
index 0000000000..ee52377b27
--- /dev/null
+++ b/assets/locales/pending/glass-material-models.json
@@ -0,0 +1,133 @@
+{
+ "ar": {
+ "render.caustics_depth": "عمق مسار تجمّع الضوء",
+ "render.caustics_enable": "تجمّع الضوء عبر الزجاج من مصادر نقطية واتجاهية",
+ "render.caustics_help": "يتحكم عدد الفوتونات في الضجيج وكلفة الحساب. يوازن نصف قطر التجميع بين التفاصيل الدقيقة والتقدير الأنعم. يتطلب CPU إضاءة غير مباشرة.",
+ "render.caustics_path_required": "يتطلب تجمّع الضوء على CPU إضاءة غير مباشرة.",
+ "render.caustics_photons": "عدد الفوتونات",
+ "render.caustics_radius": "نصف قطر التجميع",
+ "render.glass_abbe": "عدد آبي",
+ "render.glass_dispersion": "التشتت اللوني",
+ "render.glass_film": "تداخل الأغشية الرقيقة",
+ "render.glass_film_ior": "معامل انكسار الغشاء",
+ "render.glass_film_thickness": "سمك الغشاء",
+ "render.glass_model_enable": "نموذج زجاج متقدم",
+ "render.glass_model_help": "تشتت خشونة الزجاج الأشعة النافذة. يستخدم التشتت ولون الغشاء ثلاثة نطاقات طول موجي. تتطلب الصفائح الخشنة إيقاف الظلال النافذة المستقيمة.",
+ "render.glass_roughness": "خشونة الزجاج"
+ },
+ "de": {
+ "render.caustics_depth": "Kaustik-Pfadtiefe",
+ "render.caustics_enable": "Glaskaustiken durch Punkt- und Richtungslichter",
+ "render.caustics_help": "Die Photonenzahl bestimmt Rauschen und Aufwand. Der Sammelradius tauscht scharfe Details gegen eine glattere Schätzung. CPU benötigt indirekte Beleuchtung.",
+ "render.caustics_path_required": "CPU-Kaustiken benötigen indirekte Beleuchtung.",
+ "render.caustics_photons": "Photonen",
+ "render.caustics_radius": "Sammelradius",
+ "render.glass_abbe": "Abbe-Zahl",
+ "render.glass_dispersion": "Chromatische Dispersion",
+ "render.glass_film": "Dünnschichtinterferenz",
+ "render.glass_film_ior": "Brechungsindex der Schicht",
+ "render.glass_film_thickness": "Schichtdicke",
+ "render.glass_model_enable": "Erweitertes Glasmodell",
+ "render.glass_model_help": "Glasrauheit streut durchgelassene Strahlen. Dispersion und Schichtfarbe verwenden drei Wellenlängenbänder. Raue Scheiben benötigen ausgeschaltete gerade Schattenübertragung.",
+ "render.glass_roughness": "Glasrauheit"
+ },
+ "en": {
+ "render.caustics_depth": "Caustic path depth",
+ "render.caustics_enable": "Glass caustics from point and directional lights",
+ "render.caustics_help": "Photon count controls noise and work. Gather radius trades sharp detail for a smoother estimate. CPU requires Indirect lighting.",
+ "render.caustics_path_required": "CPU caustics require Indirect lighting.",
+ "render.caustics_photons": "Photons",
+ "render.caustics_radius": "Gather radius",
+ "render.glass_abbe": "Abbe number",
+ "render.glass_dispersion": "Chromatic dispersion",
+ "render.glass_film": "Thin-film interference",
+ "render.glass_film_ior": "Film IOR",
+ "render.glass_film_thickness": "Film thickness",
+ "render.glass_model_enable": "Advanced Glass model",
+ "render.glass_model_help": "Glass roughness scatters transmitted rays. Dispersion and film color use three wavelength bands. Rough sheets require straight transmitted shadows off.",
+ "render.glass_roughness": "Glass roughness"
+ },
+ "en-GB": {
+ "render.glass_model_help": "Glass roughness scatters transmitted rays. Dispersion and film colour use three wavelength bands. Rough sheets require straight transmitted shadows off."
+ },
+ "he": {
+ "render.caustics_depth": "עומק מסלול ריכוז האור",
+ "render.caustics_enable": "ריכוז אור דרך זכוכית ממקורות נקודתיים וכיווניים",
+ "render.caustics_help": "מספר הפוטונים שולט ברעש ובעומס החישוב. רדיוס האיסוף מאזן בין פרטים חדים לאומדן חלק יותר. CPU דורש תאורה עקיפה.",
+ "render.caustics_path_required": "ריכוז אור ב-CPU דורש תאורה עקיפה.",
+ "render.caustics_photons": "מספר פוטונים",
+ "render.caustics_radius": "רדיוס איסוף",
+ "render.glass_abbe": "מספר אבה",
+ "render.glass_dispersion": "נפיצה כרומטית",
+ "render.glass_film": "התאבכות בשכבה דקה",
+ "render.glass_film_ior": "מקדם שבירה של השכבה",
+ "render.glass_film_thickness": "עובי השכבה",
+ "render.glass_model_enable": "מודל זכוכית מתקדם",
+ "render.glass_model_help": "חספוס הזכוכית מפזר קרניים מועברות. נפיצה וצבע השכבה משתמשים בשלושה תחומי אורך גל. לוחות מחוספסים דורשים כיבוי צללים מועברים בקו ישר.",
+ "render.glass_roughness": "חספוס זכוכית"
+ },
+ "ja": {
+ "render.caustics_depth": "集光経路の深さ",
+ "render.caustics_enable": "点光源・平行光源によるガラスの集光",
+ "render.caustics_help": "光子数はノイズと計算量を調整します。収集半径を広げると細部より滑らかさを優先します。CPUでは間接照明が必要です。",
+ "render.caustics_path_required": "CPUの集光には間接照明が必要です。",
+ "render.caustics_photons": "光子数",
+ "render.caustics_radius": "収集半径",
+ "render.glass_abbe": "アッベ数",
+ "render.glass_dispersion": "色分散",
+ "render.glass_film": "薄膜干渉",
+ "render.glass_film_ior": "薄膜の屈折率",
+ "render.glass_film_thickness": "薄膜の厚さ",
+ "render.glass_model_enable": "高度なガラスモデル",
+ "render.glass_model_help": "ガラスの粗さは透過光を散乱させます。分散と薄膜の色は3つの波長帯を使用します。粗い薄板では直進透過影をオフにしてください。",
+ "render.glass_roughness": "ガラスの粗さ"
+ },
+ "ko": {
+ "render.caustics_depth": "집광 경로 깊이",
+ "render.caustics_enable": "점광원 및 방향광의 유리 집광",
+ "render.caustics_help": "광자 수는 노이즈와 계산량을 조절합니다. 수집 반경은 세밀한 표현과 부드러운 추정 사이를 조절합니다. CPU에는 간접 조명이 필요합니다.",
+ "render.caustics_path_required": "CPU 집광에는 간접 조명이 필요합니다.",
+ "render.caustics_photons": "광자 수",
+ "render.caustics_radius": "수집 반경",
+ "render.glass_abbe": "아베 수",
+ "render.glass_dispersion": "색 분산",
+ "render.glass_film": "박막 간섭",
+ "render.glass_film_ior": "박막 굴절률",
+ "render.glass_film_thickness": "박막 두께",
+ "render.glass_model_enable": "고급 유리 모델",
+ "render.glass_model_help": "유리 거칠기는 투과 광선을 산란시킵니다. 분산과 박막 색상은 세 파장 대역을 사용합니다. 거친 얇은 판은 직선 투과 그림자를 꺼야 합니다.",
+ "render.glass_roughness": "유리 거칠기"
+ },
+ "vi": {
+ "render.caustics_depth": "Độ sâu đường tụ quang",
+ "render.caustics_enable": "Tụ quang qua kính từ nguồn điểm và nguồn định hướng",
+ "render.caustics_help": "Số photon điều chỉnh nhiễu và khối lượng tính toán. Bán kính thu thập đánh đổi chi tiết sắc nét để có ước lượng mượt hơn. CPU cần chiếu sáng gián tiếp.",
+ "render.caustics_path_required": "Tụ quang trên CPU cần chiếu sáng gián tiếp.",
+ "render.caustics_photons": "Số photon",
+ "render.caustics_radius": "Bán kính thu thập",
+ "render.glass_abbe": "Số Abbe",
+ "render.glass_dispersion": "Tán sắc màu",
+ "render.glass_film": "Giao thoa màng mỏng",
+ "render.glass_film_ior": "Chiết suất màng",
+ "render.glass_film_thickness": "Độ dày màng",
+ "render.glass_model_enable": "Mô hình kính nâng cao",
+ "render.glass_model_help": "Độ nhám kính làm tán xạ tia truyền qua. Tán sắc và màu màng dùng ba dải bước sóng. Tấm nhám cần tắt bóng truyền thẳng.",
+ "render.glass_roughness": "Độ nhám kính"
+ },
+ "zh": {
+ "render.caustics_depth": "焦散路径深度",
+ "render.caustics_enable": "点光源和方向光的玻璃焦散",
+ "render.caustics_help": "光子数控制噪点和计算量。增大收集半径可得到更平滑的估计,但会损失细节。CPU需要间接照明。",
+ "render.caustics_path_required": "CPU焦散需要间接照明。",
+ "render.caustics_photons": "光子数",
+ "render.caustics_radius": "收集半径",
+ "render.glass_abbe": "阿贝数",
+ "render.glass_dispersion": "色散",
+ "render.glass_film": "薄膜干涉",
+ "render.glass_film_ior": "薄膜折射率",
+ "render.glass_film_thickness": "薄膜厚度",
+ "render.glass_model_enable": "高级玻璃模型",
+ "render.glass_model_help": "玻璃粗糙度会散射透射光线。色散和薄膜颜色使用三个波长波段。粗糙薄片需要关闭直线透射阴影。",
+ "render.glass_roughness": "玻璃粗糙度"
+ }
+}
diff --git a/assets/locales/vi.json b/assets/locales/vi.json
index 4916e30707..88bdc632a7 100644
--- a/assets/locales/vi.json
+++ b/assets/locales/vi.json
@@ -3191,7 +3191,7 @@
"render.category_wood": "Gỗ",
"render.check_glass_cpu": "CPU hỗ trợ các tấm kính phẳng và hộp thẳng theo trục đã được kiểm chứng. Lưới kín tổng quát, cấu trúc lồng nhau và tán xạ bên trong cần Chiếu sáng gián tiếp. Chưa hỗ trợ bóng truyền qua kính kín.",
"render.check_glass_gpu": "GPU hỗ trợ các khối kính tách rời đã được kiểm chứng hoặc cấu trúc lồng nhau được kiểm chứng và bật rõ ràng. Cấu trúc lồng nhau cần lớp bao lồi, vật thể con nằm hoàn toàn bên trong và các ranh giới không chạm nhau.",
- "render.check_media_remaining": "Chưa hỗ trợ kính nhám, lưới mật độ, dịch chuyển bề mặt và truyền sáng quang phổ.",
+ "render.check_media_remaining": "Lưới mật độ, dịch chuyển bề mặt, tích phân toàn phổ và truyền trạng thái phân cực vẫn chưa được hỗ trợ.",
"render.check_media_scope": "Tán xạ bên trong đang hoạt động cần môi trường kính kín, tắt truyền tia bóng thẳng và tắt Khử nhiễu. GPU cũng cần một tầng Fresnel. Không thể kết hợp Khí quyển bên ngoài đang hoạt động với kính hoặc Khử nhiễu bề mặt.",
"render.check_opaque": "Độ trong suốt: chỉ bề mặt đục; hỗ trợ alpha của phông nền.",
"render.check_sorted_alpha": "Độ trong suốt: xấp xỉ alpha có sắp thứ tự.",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index 5b4f314502..0efe606cb6 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -3191,7 +3191,7 @@
"render.category_wood": "木材",
"render.check_glass_cpu": "CPU 支持经验证的平面玻璃薄片和轴对齐盒体。一般闭合网格、嵌套和内部散射需要间接光照。仍不支持穿过闭合玻璃的透射阴影。",
"render.check_glass_gpu": "GPU 支持经验证的互不相交玻璃介质,或明确启用的经验证嵌套。嵌套要求外层物体为凸体、内层物体严格包含于其中,且边界互不接触。",
- "render.check_media_remaining": "仍不支持粗糙玻璃、密度网格、位移和光谱传输。",
+ "render.check_media_remaining": "密度网格、置换、完整光谱积分和偏振状态传播仍不受支持。",
"render.check_media_scope": "启用内部散射需要闭合玻璃介质,并关闭直线阴影透射和降噪。GPU 还需要只使用一个菲涅耳分层。启用的外部大气不能与玻璃或表面降噪同时使用。",
"render.check_opaque": "透明度:仅不透明表面;支持背景 Alpha。",
"render.check_sorted_alpha": "透明度:排序 Alpha 近似。",
diff --git a/crates/doc/src/format/pending/glass-material-models.rs b/crates/doc/src/format/pending/glass-material-models.rs
new file mode 100644
index 0000000000..38448192b9
--- /dev/null
+++ b/crates/doc/src/format/pending/glass-material-models.rs
@@ -0,0 +1,8 @@
+//! Glass assignments can save optional `model` roughness, Abbe dispersion and a
+//! coherent dielectric film (IOR and thickness in nanometres). Omission retains
+//! the preceding smooth, nondispersive interface and incoherent sheet response.
+//! CPU and GPU jobs can save optional `caustics` photon count, gather radius in
+//! millimetres, light-path depth and seed. Omission creates no photon map and
+//! retains preceding sampling. Older releases ask for an update rather than
+//! discard these authored material and light-transport choices. No migration of
+//! existing designs, geometry, engineering material or saved camera is required.
diff --git a/crates/doc/src/render_job.rs b/crates/doc/src/render_job.rs
index bc2345a29c..569ea1faa6 100644
--- a/crates/doc/src/render_job.rs
+++ b/crates/doc/src/render_job.rs
@@ -82,6 +82,8 @@ impl RenderJob {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CpuJob {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub caustics: Option<solidcraft_render::job::CausticOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub volume: Option<solidcraft_render::job::volume::HomogeneousVolume>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -127,6 +129,7 @@ pub struct CpuJob {
impl Default for CpuJob {
fn default() -> Self {
Self {
+ caustics: None,
volume: None,
sun: None,
sky: None,
@@ -197,6 +200,7 @@ impl CpuJob {
})
.transpose()?;
let options = RaytraceOptions {
+ caustics: self.caustics,
volume: self.volume,
sun: self.sun.map(Box::new),
sky,
@@ -229,6 +233,8 @@ impl CpuJob {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct GpuJob {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub caustics: Option<solidcraft_render::job::CausticOptions>,
#[serde(skip_serializing_if = "crate::render_aging::SavedAgingStack::is_empty")]
pub aging: crate::render_aging::SavedAgingStack,
pub nested_media: bool,
@@ -263,6 +269,7 @@ impl Default for GpuJob {
fn default() -> Self {
let options = JobOptions::default();
Self {
+ caustics: None,
aging: Default::default(),
nested_media: options.nested_media,
volume: options.volume,
@@ -310,6 +317,7 @@ impl GpuJob {
environment.validate()?;
}
let options = JobOptions {
+ caustics: self.caustics,
aging: self.aging.parameters_only()?,
nested_media: self.nested_media,
volume: self.volume,
diff --git a/crates/doc/src/render_optics.rs b/crates/doc/src/render_optics.rs
index a095bb46f5..7396a7a278 100644
--- a/crates/doc/src/render_optics.rs
+++ b/crates/doc/src/render_optics.rs
@@ -23,6 +23,8 @@ pub enum OpticalBoundary {
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct OpticalMaterial {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub model: Option<solidcraft_render::glass_model::GlassModel>,
pub ior: f64,
pub absorption_per_mm: [f64; 3],
pub boundary: OpticalBoundary,
@@ -32,7 +34,15 @@ pub struct OpticalMaterial {
}
impl Default for OpticalMaterial {
fn default() -> Self {
- Self { ior: 1.5, absorption_per_mm: [0.0; 3], boundary: Default::default(), thickness_mm: 0.0, shadow_transmission: false, subsurface: None }
+ Self {
+ model: None,
+ ior: 1.5,
+ absorption_per_mm: [0.0; 3],
+ boundary: Default::default(),
+ thickness_mm: 0.0,
+ shadow_transmission: false,
+ subsurface: None,
+ }
}
}
impl OpticalMaterial {
@@ -44,6 +54,9 @@ impl OpticalMaterial {
/// General closed boundaries require the explicit finite progressive path.
pub fn validate_for_cpu_path(self, path: bool) -> Result<()> {
self.validate()?;
+ if self.model.is_some() && !path {
+ return Err(DocError::Invalid("advanced Glass models require CPU Indirect lighting".into()));
+ }
if self.shadow_transmission && (!path || self.boundary != OpticalBoundary::ThinSheet) {
return Err(DocError::Invalid(
"CPU transmissive shadows require Indirect lighting and a thin sheet; closed refractive light connections remain unsupported".into(),
@@ -70,6 +83,7 @@ impl OpticalMaterial {
return Err(DocError::Invalid("CPU optical target requires a bounded captured body name".into()));
}
Ok(solidcraft_render::job::DielectricOptions {
+ model: self.model,
subsurface: self.subsurface,
shadow_transmission: self.shadow_transmission,
body_index,
@@ -87,6 +101,12 @@ impl OpticalMaterial {
pub fn validate(self) -> Result<()> {
let error = |message: String| DocError::Invalid(message);
+ if let Some(model) = self.model {
+ model.validate(self.ior).map_err(|e| error(e.to_string()))?;
+ if self.boundary == OpticalBoundary::ThinSheet && self.shadow_transmission && model.roughness > 0.0 {
+ return Err(error("rough thin-sheet Glass requires disabled straight transmitted shadows".into()));
+ }
+ }
OpaqueSurface::new(Vec3::ZERO, 0.0, 0.5, self.ior).map_err(|e| error(e.to_string()))?;
if self.boundary != OpticalBoundary::ThinSheet && self.thickness_mm != 0.0 {
return Err(error("closed optical thickness comes from geometry; thickness_mm must be zero".into()));
@@ -187,6 +207,48 @@ impl<'de> Deserialize<'de> for OpticalBindings {
Ok(result)
}
}
+
+#[cfg(test)]
+mod advanced_model_contract_tests {
+ use super::*;
+ use solidcraft_render::glass_model::{Dispersion, GlassModel, ThinFilm};
+ #[test]
+ fn advanced_optics_keep_every_authored_number_through_saved_and_cpu_lowering() {
+ let model = GlassModel {
+ roughness: 0.27,
+ dispersion: Some(Dispersion { abbe_number: 45.0 }),
+ thin_film: Some(ThinFilm { ior: 1.36, thickness_nm: 420.0 }),
+ };
+ let optics = OpticalMaterial { model: Some(model), ..Default::default() };
+ let wire = serde_json::to_value(optics).unwrap();
+ assert_eq!(serde_json::from_value::<OpticalMaterial>(wire.clone()).unwrap(), optics);
+ assert_eq!(optics.to_cpu_for_path(2, "Original Glass", true).unwrap().model, Some(model));
+ assert!(optics.to_cpu(2, "Original Glass").is_err());
+ assert_eq!(serde_json::to_value(optics).unwrap(), wire);
+ assert!(serde_json::to_value(OpticalMaterial::default()).unwrap().get("model").is_none());
+ let sheet = OpticalMaterial {
+ model: Some(GlassModel { roughness: 0.0, ..model }),
+ boundary: OpticalBoundary::ThinSheet,
+ shadow_transmission: true,
+ ..optics
+ };
+ sheet.validate_for_cpu_path(true).unwrap();
+ assert!(OpticalMaterial { model: Some(model), ..sheet }.validate().is_err());
+ }
+ #[test]
+ fn caustic_quality_is_portable_between_both_saved_jobs_and_runtime_requests() {
+ use crate::render_job::{CpuJob, GpuJob};
+ let caustics = Some(solidcraft_render::job::CausticOptions { photons: 8192, radius_mm: 0.4, max_depth: 12, seed: 381 });
+ let cpu = CpuJob { caustics, path: Some(Default::default()), progressive: Some(Default::default()), ..Default::default() };
+ let gpu = GpuJob { caustics, ..Default::default() };
+ assert_eq!(cpu.to_runtime(0.0).unwrap().caustics, caustics);
+ assert_eq!(gpu.to_runtime(0.0).unwrap().caustics, caustics);
+ assert_eq!(serde_json::from_value::<CpuJob>(serde_json::to_value(&cpu).unwrap()).unwrap(), cpu);
+ assert_eq!(serde_json::from_value::<GpuJob>(serde_json::to_value(&gpu).unwrap()).unwrap(), gpu);
+ assert!(serde_json::to_value(CpuJob::default()).unwrap().get("caustics").is_none());
+ assert!(serde_json::to_value(GpuJob::default()).unwrap().get("caustics").is_none());
+ }
+}
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs
index 2d42e74620..d602e78c70 100644
--- a/crates/engine/src/cmd/render.rs
+++ b/crates/engine/src/cmd/render.rs
@@ -92,7 +92,7 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.optics.bind","Save Optical Binding",crate::checked!("render.optics.bind", optical_bindings::bind)).icon("appearance")
.contract(&optical_bindings::BIND_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render_bindings::OpticsBindingSaved>)
- .params("name: CPU or GPU setup; set?: complete numerical setup patch; body_index and body_name: exact captured target; expected_revision; optics:{ior,absorption_per_mm:[r,g,b],boundary:closed_mesh|closed_box|thin_sheet,thickness_mm,shadow_transmission,subsurface?:{scattering_per_mm,anisotropy}}; replace?:false. Stores stable definition/feature/occurrence identity in one undo without modifying engineering geometry/materials. CPU consumes at most eight certified optical targets. Without options.path, sheets and axis-aligned boxes retain the existing transport. Explicit progressive options.path enables exact closed-mesh certification, bounded nested convex-parent media, Beer/Snell/Fresnel and thin transmitted shadows; touching or unproven boundaries and closed transmitted-shadow connections refuse explicitly. Existing subsurface parameters may be consumed on certified closed Path media with denoising explicitly off; scalar free-flight/HG walks and separate Beer absorption are supported without refracting-boundary next-event approximation. A zero scattering rate preserves transport. GPU nested media require separate job.options.nested_media and producer certification. Unresolved or incompatible targets refuse atomically."),
+ .params("name: CPU or GPU setup; set?: complete numerical setup patch; body_index and body_name: exact captured target; expected_revision; optics:{ior,absorption_per_mm:[r,g,b],boundary:closed_mesh|closed_box|thin_sheet,thickness_mm,shadow_transmission,subsurface?:{scattering_per_mm,anisotropy},model?:{roughness:0..1,dispersion?:{abbe_number:5..200},thin_film?:{ior:1..3,thickness_nm:0..100000}}}; replace?:false. The optional model adds isotropic rough transmission, three-band dispersion and one lossless coherent film. CPU models require explicit Path; rough sheets require straight transmitted shadows off. See docs/render-glass-material-models.md. Stores stable definition/feature/occurrence identity in one undo without modifying engineering geometry/materials. CPU consumes at most eight certified optical targets. Without options.path, sheets and axis-aligned boxes retain the existing transport. Explicit progressive options.path enables exact closed-mesh certification, bounded nested convex-parent media, Beer/Snell/Fresnel and thin transmitted shadows; touching or unproven boundaries and closed transmitted-shadow connections refuse explicitly. Existing subsurface parameters may be consumed on certified closed Path media with denoising explicitly off; scalar free-flight/HG walks and separate Beer absorption are supported without refracting-boundary next-event approximation. A zero scattering rate preserves transport. GPU nested media require separate job.options.nested_media and producer certification. Unresolved or incompatible targets refuse atomically."),
CommandSpec::new("render.optics.unbind","Remove Optical Binding",crate::checked!("render.optics.unbind", optical_bindings::unbind)).icon("appearance").doc_only()
.contract(&optical_bindings::UNBIND_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render_bindings::OpticsUnbound>)
@@ -188,7 +188,7 @@ CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR",
.output(crate::schema::output_schema_for::<crate::schema::render_hdr::HdrCaptured>)
.params("name, set: typed CPU/GPU setup patch with hdr/environment unset; path: scoped HDR; expected_sha256?: digest returned by render.hdr.inspect (changed sources refuse); rotation_rad?:0, intensity?:1; samples?:1/4/16/64 for CPU only (default16); assume_linear_srgb?:false for GPU only. Captures immutable bytes and saves resource plus setup atomically in one undo, without a host; returns name/setup/resource metadata, never source bytes"),
CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only()
- .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace and transient studio_weights may accompany it. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.lens?: {aperture_radius_mm:0..10000000,focus_distance_mm:0.000001..1000000000}; positive aperture requires explicit CPU progressive sampling and a bounded perspective camera; absent/zero keeps the original CPU ray stream. See docs/render-thin-lens.md. CPU raytrace.volume?: one HomogeneousVolume box with world-mm min_mm/max_mm, extinction_per_mm:0..1000, RGB scattering_albedo:0..1 and anisotropy:-0.95..0.95. Positive extinction requires explicit Indirect lighting and cannot combine with Glass/SSS or surface Denoise. Physical eye/pupil prefixes and the orthographic line/box union preserve camera/model framing under existing ray/profile caps. See docs/render-cpu-volume.md. CPU raytrace.sun? uses the shared finite-disk Sun contract; raytrace.sky? uses {gradient,rotation_rad,intensity}. Both require explicit Indirect lighting, and gradient Sky excludes a constant/HDR environment. Their medium NEE uses the HG response/PDF and physical light source; see docs/render-cpu-celestial.md. CPU transparent_background?:false exports straight-alpha primary geometry coverage for fixed/progressive sampling; body/face opacity must remain 1, and active bloom/backdrop/photographic effects require opaque output. CPU raytrace.output?: {tone_map,finishing,backdrop,linear_exr}; shared presentation supports up to 8192 per side and 16777216 pixels, CPU exposure remains raytrace.exposure_ev; raw FLOAT32 EXR is retained only at final completion. 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; area/LED sources and certified planar anisotropy/thin-sheet/axis-aligned-box dielectric continuations share the existing bounded transport and compatibility checks. 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. Optional raytrace.path:{max_depth:1..16} enables CPU diffuse/specular GI with matched rectangle/HDR light and BSDF MIS plus certified closed-mesh Glass. It requires explicit progressive camera sampling, primary_samples:1 and traced shadows; selected reflections and certified anisotropy refuse before HDR IO without changing intent. CPU Path dielectric subsurface?:{scattering_per_mm:0..100,anisotropy:-0.95..0.95} enables homogeneous free-flight/HG walks inside certified closed media; positive rates require denoising off. Contained light connections include scattering survival; closed refractive light connections and combining Glass with external volume remain unsupported. Absent path keeps the old certified thin_sheet/closed_box producer and refuses subsurface intent explicitly. See docs/render-cpu-general-glass.md and render-raytrace-dielectrics.md. CPU emissions are visible radiance and may light neighbors through sampled Path continuation, without mesh-emitter next-event sampling; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/64 for the whole strip, default16. At most8directional+8punctual+4rectangle/LED sources; shared area N. See docs/render-light-union.md. transparent_background?: false; replace?: false. With progressive:true, raytrace instead accepts GPU dielectrics/clear_coats/textures; environment instead accepts tagged hdr/embedded_hdr/sky with rotation_rad/intensity; file hdr supports expected_sha256, embedded_hdr uses a document resource digest. See docs/render-hdr-resources.md. GPU lens, studio lighting, tone_map, denoise, bounded finishing/backdrop and linear_exr retention are also available. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"),
+ .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace and transient studio_weights may accompany it. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.lens?: {aperture_radius_mm:0..10000000,focus_distance_mm:0.000001..1000000000}; positive aperture requires explicit CPU progressive sampling and a bounded perspective camera; absent/zero keeps the original CPU ray stream. See docs/render-thin-lens.md. CPU raytrace.volume?: one HomogeneousVolume box with world-mm min_mm/max_mm, extinction_per_mm:0..1000, RGB scattering_albedo:0..1 and anisotropy:-0.95..0.95. Positive extinction requires explicit Indirect lighting and cannot combine with Glass/SSS or surface Denoise. Physical eye/pupil prefixes and the orthographic line/box union preserve camera/model framing under existing ray/profile caps. See docs/render-cpu-volume.md. CPU raytrace.sun? uses the shared finite-disk Sun contract; raytrace.sky? uses {gradient,rotation_rad,intensity}. Both require explicit Indirect lighting, and gradient Sky excludes a constant/HDR environment. Their medium NEE uses the HG response/PDF and physical light source; see docs/render-cpu-celestial.md. CPU transparent_background?:false exports straight-alpha primary geometry coverage for fixed/progressive sampling; body/face opacity must remain 1, and active bloom/backdrop/photographic effects require opaque output. CPU raytrace.output?: {tone_map,finishing,backdrop,linear_exr}; shared presentation supports up to 8192 per side and 16777216 pixels, CPU exposure remains raytrace.exposure_ev; raw FLOAT32 EXR is retained only at final completion. 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; area/LED sources and certified planar anisotropy/thin-sheet/axis-aligned-box dielectric continuations share the existing bounded transport and compatibility checks. 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. Optional raytrace.path:{max_depth:1..16} enables CPU diffuse/specular GI with matched rectangle/HDR light and BSDF MIS plus certified closed-mesh Glass. It requires explicit progressive camera sampling, primary_samples:1 and traced shadows; selected reflections and certified anisotropy refuse before HDR IO without changing intent. CPU Path dielectric subsurface?:{scattering_per_mm:0..100,anisotropy:-0.95..0.95} enables homogeneous free-flight/HG walks inside certified closed media; positive rates require denoising off. Contained light connections include scattering survival; closed refractive light connections and combining Glass with external volume remain unsupported. Absent path keeps the old certified thin_sheet/closed_box producer and refuses subsurface intent explicitly. See docs/render-cpu-general-glass.md and render-raytrace-dielectrics.md. CPU emissions are visible radiance and may light neighbors through sampled Path continuation, without mesh-emitter next-event sampling; 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. Both methods accept optional caustics {photons:1..65536,radius_mm:0.000001..1000000,max_depth:1..16,seed:u32} (inside CPU raytrace; top-level GPU). Optical assignments accept optional model {roughness:0..1,dispersion?:{abbe_number:5..200},thin_film?:{ior:1..3,thickness_nm:0..100000}}. CPU advanced models require Path; rough sheets require straight transmitted shadows off. See docs/render-glass-material-models.md. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"),
CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image")
.params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"),
CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only()
diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rs
index baebd37c38..a5a18340fe 100644
--- a/crates/engine/src/cmd/render/job_tests.rs
+++ b/crates/engine/src/cmd/render/job_tests.rs
@@ -3533,3 +3533,118 @@ mod native_camera_queue_preparation {
assert_eq!(host.admitted_bytes(), 0);
}
}
+
+#[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))]
+#[test]
+fn tessellated_cpu_sheet_saved_and_prospective_bindings_certify_and_render_without_saving_the_draft() {
+ use solidcraft_doc::render_optics::{OpticalBoundary, OpticalMaterial, SavedOptics};
+ use solidcraft_render::job::{ImageRequest, Phase};
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let directory = std::env::temp_dir().join(format!("solidcraft-cpu-path-tiled-sheets-{}-{nonce}", std::process::id()));
+ std::fs::create_dir(&directory).unwrap();
+ let mut s = Session::default();
+ for (name, offset) in [("SavedSheet", 0), ("DraftSheet", 30)] {
+ let path = directory.join(format!("{name}.obj"));
+ let mut source = format!("o {name}\n");
+ for y in 0..2 {
+ for x in 0..2 {
+ let x = offset - 10 + x * 10;
+ let y = -10 + y * 10;
+ source.push_str(&format!("v {x} {y} 0\nv {} {y} 0\nv {} {} 0\nv {x} {} 0\n", x + 10, x + 10, y + 10, y + 10));
+ }
+ }
+ for cell in 0..4 {
+ let index = cell * 4 + 1;
+ source.push_str(&format!("f {index} {} {}\nf {index} {} {}\n", index + 1, index + 2, index + 2, index + 3));
+ }
+ std::fs::write(&path, source).unwrap();
+ s.execute("file.insert_mesh", &json!({"path":path})).unwrap();
+ }
+ let scene = crate::product_scene::extract(&s).unwrap();
+ assert_eq!(scene.meshes.len(), 2);
+ assert!(scene.meshes.iter().all(|body| body.mesh.triangles.len() == 8));
+ let saved_name = scene.meshes[0].name.clone();
+ let draft_name = scene.meshes[1].name.clone();
+ let targets = s.execute("render.library.targets", &json!({})).unwrap();
+ let draft_target = targets["items"].as_array().unwrap().iter().find(|row| row["name"] == draft_name).unwrap()["stable_target"].clone();
+ let mut camera = solidcraft_render::Camera { target: solidcore_record::Vec3::new(15.0, 0.0, 0.0), distance: 30.0, ..Default::default() };
+ camera.set_view(solidcraft_render::StandardView::Top);
+ s.execute(
+ "render.settings.set",
+ &json!({"name":"Sheets","set":{"camera":camera,"width":8,"height":4,
+ "job":{"method":"cpu_raytrace","options":{"path":{"max_depth":8},"progressive":{"samples_per_pixel":4,"seed":81},
+ "lights":[],"environment":{"color":[1,1,1],"intensity":1},"output":{"linear_exr":true}}}}}),
+ )
+ .unwrap();
+ s.execute(
+ "render.optics.bind",
+ &json!({"name":"Sheets","body_index":0,"body_name":saved_name,"expected_revision":s.revision,
+ "optics":{"boundary":"thin_sheet","ior":1,"thickness_mm":2,"absorption_per_mm":[0.1,0.2,0]}}),
+ )
+ .unwrap();
+ let persisted = solidcraft_io::write_design_container(&s.doc).unwrap();
+ std::fs::remove_dir_all(directory).unwrap();
+ s = Session::new(solidcraft_io::read_design(&persisted).unwrap());
+ s.execute("render.scene", &json!({})).unwrap();
+ let saved = s.doc.render.setups["Sheets"].clone();
+ let mut draft = saved.clone();
+ draft
+ .optics
+ .set(
+ SavedOptics {
+ target: serde_json::from_value(draft_target).unwrap(),
+ optics: OpticalMaterial {
+ boundary: OpticalBoundary::ThinSheet,
+ ior: 1.0,
+ thickness_mm: 2.0,
+ absorption_per_mm: [0.3, 0.0, 0.2],
+ ..Default::default()
+ },
+ },
+ false,
+ )
+ .unwrap();
+ let host = CpuHost::for_platform().unwrap();
+ s.set_render_job_host(Some(host.clone())).unwrap();
+ let document = s.doc.clone();
+ let geometry = s.model.state();
+ let history = (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty());
+ let named = s.execute("render.preflight", &json!({"setup":"Sheets"})).unwrap();
+ let checked = s.execute("render.preflight", &json!({"settings":draft})).unwrap();
+ assert_eq!(named["request"]["raytrace"]["dielectrics"].as_array().unwrap().len(), 1);
+ let captured: ImageRequest = serde_json::from_value(checked["request"].clone()).unwrap();
+ let optics = &captured.raytrace.as_ref().unwrap().dielectrics;
+ assert_eq!(optics.len(), 2, "prospective stable optics add to the saved binding");
+ for (name, absorption) in [(&saved_name, [0.1, 0.2, 0.0]), (&draft_name, [0.3, 0.0, 0.2])] {
+ let input = optics.iter().find(|input| input.body_name == *name).unwrap();
+ assert_eq!(input.boundary, solidcraft_render::job::DielectricBoundary::ThinSheet);
+ assert_eq!((input.ior, input.thickness_mm, input.absorption_per_mm), (1.0, 2.0, absorption));
+ }
+ let runtime = json!({"integrator":"raytrace","settings":{"camera":camera,"width":8,"height":4},"raytrace":captured.raytrace});
+ assert_eq!(s.execute("render.preflight", &runtime).unwrap()["request"], checked["request"]);
+ let mut legacy = json!({"settings":draft});
+ legacy["settings"]["job"]["options"].as_object_mut().unwrap().remove("path");
+ assert!(
+ s.execute("render.preflight", &legacy).unwrap_err().to_string().contains("unsupported dielectric boundary tessellation"),
+ "successful Path checks must actually certify the eight-triangle mesh, not just forward optics metadata"
+ );
+ assert_eq!(host.admitted_bytes(), 0, "Check releases its complete preparation certificate");
+ let run = |s: &mut Session, params: Value| {
+ let started = s.execute("render.start", &params).unwrap();
+ let job = serde_json::from_value(started["job"].clone()).unwrap();
+ let handle = s.render_job_handle(job).unwrap();
+ let status = handle.wait_timeout(std::time::Duration::from_secs(30)).unwrap();
+ assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
+ let frame = handle.frame().unwrap().unwrap();
+ (frame.png().to_vec(), frame.linear_exr().unwrap().to_vec())
+ };
+ let original = run(&mut s, json!({"setup":"Sheets"}));
+ let prospective = run(&mut s, json!({"settings":draft,"replace":true}));
+ assert_ne!(original, prospective, "the second prospective optical assignment must change the actual pixels");
+ let mut runtime = runtime;
+ runtime["replace"] = json!(true);
+ assert_eq!(prospective, run(&mut s, runtime));
+ assert_eq!(s.doc.render.setups["Sheets"], saved);
+ assert!(Arc::ptr_eq(&document, &s.doc) && Arc::ptr_eq(&geometry, &s.model.state()));
+ assert_eq!(history, (s.revision, s.evaluations, s.undo.len(), s.redo.len(), s.is_dirty()));
+}
diff --git a/crates/engine/src/cmd/render/jobs.rs b/crates/engine/src/cmd/render/jobs.rs
index a3948f2b48..2162c32d45 100644
--- a/crates/engine/src/cmd/render/jobs.rs
+++ b/crates/engine/src/cmd/render/jobs.rs
@@ -48,6 +48,7 @@ impl Default for EnvironmentRequest {
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct ProgressiveStart {
+ caustics: Option<solidcraft_render::job::CausticOptions>,
studio_weights: Option<[f64; 3]>,
aging: solidcraft_doc::render_aging::SavedAgingStack,
#[serde(default)]
@@ -193,7 +194,7 @@ fn normalize_saved_job(s: &Session, params: &Value, command: &str) -> Result<Opt
"lens":options.lens,"lighting":options.lighting,"tone_map":options.tone_map,
"denoise":options.denoise,"environment":options.environment,
"finishing":options.finishing,"backdrop":options.backdrop,"linear_exr":options.linear_exr,
- "adaptive":options.adaptive,"transmission_samples":options.transmission_samples,"volume":options.volume,"nested_media":options.nested_media,"aging":options.aging
+ "caustics":options.caustics,"adaptive":options.adaptive,"transmission_samples":options.transmission_samples,"volume":options.volume,"nested_media":options.nested_media,"aging":options.aging
})
}
};
@@ -715,6 +716,7 @@ fn prepare_progressive(
options.aging = super::effects::resolve_aging(s, &scene, &input.aging, command)?;
options.nested_media = input.nested_media;
options.volume = input.volume;
+ options.caustics = input.caustics;
options.adaptive = input.adaptive;
options.transmission_samples = input.transmission_samples.unwrap_or(1);
options.validate().map_err(job_error)?;
diff --git a/crates/engine/src/cmd/render/transmission.rs b/crates/engine/src/cmd/render/transmission.rs
index bec310e97f..264be5538d 100644
--- a/crates/engine/src/cmd/render/transmission.rs
+++ b/crates/engine/src/cmd/render/transmission.rs
@@ -41,6 +41,8 @@ fn bounded_dielectrics<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::R
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Override {
+ #[serde(default)]
+ model: Option<solidcraft_render::glass_model::GlassModel>,
body_index: usize,
body_name: String,
ior: f64,
@@ -92,6 +94,10 @@ pub(super) fn apply(scene: &mut ProductScene, overrides: &[Override], command: &
}
let [r, g, b] = input.absorption_per_mm;
let mut transmission = Transmission::new(Vec3::new(r, g, b), thickness).map_err(|e| bad(command, e.to_string()))?;
+ if let Some(model) = input.model {
+ model.validate(input.ior).map_err(|e| bad(command, e.to_string()))?;
+ transmission = transmission.with_model(model).map_err(|e| bad(command, e.to_string()))?;
+ }
if let Some(enabled) = input.shadow_transmission {
transmission = transmission.with_shadow_transmission(enabled);
}
diff --git a/crates/engine/src/schema/render_bindings.rs b/crates/engine/src/schema/render_bindings.rs
index e3cce6ca2e..4c3746192e 100644
--- a/crates/engine/src/schema/render_bindings.rs
+++ b/crates/engine/src/schema/render_bindings.rs
@@ -88,6 +88,39 @@ fn optics_schema(_: &mut SchemaGenerator) -> Schema {
"boundary": {"description": "How the body's surface bounds the medium: `thin_sheet` (a sheet of `thickness_mm`), `closed_box` or `closed_mesh` (the thickness comes from the geometry). Default: closed_mesh.", "type": "string", "enum": ["thin_sheet", "closed_box", "closed_mesh"]},
"thickness_mm": {"description": "A thin sheet's thickness (mm); 0 for a closed boundary. Default: 0.", "type": "number", "minimum": 0},
"shadow_transmission": {"description": "Let light through for shadows too. Default: false.", "type": "boolean"},
+ "model": {
+ "description": "Advanced Glass interface. Default: null (no model). A model requires the interface IOR to stay in [1, 3], including the full 380 to 780 nm range when dispersion is enabled.",
+ "type": ["object", "null"],
+ "default": null,
+ "properties": {
+ "roughness": {
+ "description": "Isotropic roughness, from 0 (smooth) to 1. Very small positive values can exceed transport precision. Default: 0.",
+ "type": "number", "minimum": 0, "maximum": 1, "default": 0
+ },
+ "dispersion": {
+ "description": "Three-band chromatic dispersion. Default: null (no dispersion).",
+ "type": ["object", "null"],
+ "default": null,
+ "properties": {
+ "abbe_number": {"description": "Abbe number, from 5 to 200.", "type": "number", "minimum": 5, "maximum": 200}
+ },
+ "required": ["abbe_number"],
+ "additionalProperties": false
+ },
+ "thin_film": {
+ "description": "One lossless film. Default: null (no film).",
+ "type": ["object", "null"],
+ "default": null,
+ "properties": {
+ "ior": {"description": "Film refractive index, from 1 to 3.", "type": "number", "minimum": 1, "maximum": 3},
+ "thickness_nm": {"description": "Film thickness in nm, from 0 to 100000. Zero has no film effect.", "type": "number", "minimum": 0, "maximum": 100000}
+ },
+ "required": ["ior", "thickness_nm"],
+ "additionalProperties": false
+ }
+ },
+ "additionalProperties": false
+ },
"subsurface": {
"description": "Light scattering inside the body, as in wax or skin; `null` for none. Default: none.",
"anyOf": [
diff --git a/crates/engine/src/schema/render_bindings_tests.rs b/crates/engine/src/schema/render_bindings_tests.rs
index 59075ad803..be9498a69f 100644
--- a/crates/engine/src/schema/render_bindings_tests.rs
+++ b/crates/engine/src/schema/render_bindings_tests.rs
@@ -38,6 +38,37 @@ fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<OpticsUnbindParams>(), &["expected_revision", "name", "target"]);
}
+#[test]
+fn advanced_glass_optics_matches_the_schema_and_the_saved_binding() {
+ let input = input_schema_for::<OpticsBindParams>();
+ let input = input.as_value();
+ let optics = &input["properties"]["optics"];
+ for (value, expected) in [
+ (json!({}), true),
+ (json!({"model": null}), true),
+ (json!({"model": {}}), true),
+ (json!({"model": {"dispersion": null, "thin_film": null}}), true),
+ (json!({"model": {"roughness": 1.01}}), false),
+ (json!({"model": {"dispersion": {}}}), false),
+ (json!({"model": {"dispersion": {"abbe_number": 4.99}}}), false),
+ (json!({"model": {"thin_film": {"ior": 1.37}}}), false),
+ (json!({"model": {"thin_film": {"ior": 3.01, "thickness_nm": 263}}}), false),
+ (json!({"model": {"thin_film": {"ior": 1.37, "thickness_nm": 100001}}}), false),
+ (json!({"model": {"thin_film": {"ior": 1.37, "thickness_nm": 263, "extra": true}}}), false),
+ ] {
+ assert_eq!(conforms(input, optics, &value), expected, "{value}");
+ }
+
+ let mut session = with_a_studio(ParamCheck::Strict);
+ let mut request = optics_on_the_lens(session.revision);
+ let model = json!({"roughness": 0.43, "dispersion": {"abbe_number": 57.0}, "thin_film": {"ior": 1.37, "thickness_nm": 263.0}});
+ request["optics"] = json!({"ior": 1.45, "model": &model});
+ assert!(conforms(input, input, &request), "{request}");
+ let reply = session.execute("render.optics.bind", &request).unwrap();
+ assert_eq!(reply["setup"]["optics"][0]["optics"]["model"], model);
+ assert_eq!(reply["geometry_and_engineering_unchanged"], true);
+}
+
/// The handlers refuse these calls after reading them; strict refuses them with their message.
/// They need a body, a saved setup and the design's revision, so the shared helper, which has
/// a sketch only, doesn't fit.
diff --git a/crates/gpu/examples/glass_comparison.rs b/crates/gpu/examples/glass_comparison.rs
new file mode 100644
index 0000000000..de520af602
--- /dev/null
+++ b/crates/gpu/examples/glass_comparison.rs
@@ -0,0 +1,472 @@
+//! Original, headless CPU/GPU Glass evidence. This is not an application or image-quality acceptance test.
+//! Run with `--features solidcraft-render/raytrace-cpu`; output directory must not exist.
+use serde_json::json;
+use solidcore_record::Vec3;
+use solidcraft_geom::{Aabb3, Mesh, Vec3Geom};
+use solidcraft_render::{
+ Camera, ProductMesh, ProductScene,
+ glass_model::{Dispersion, GlassModel, ThinFilm},
+ job::{
+ AreaLight, AreaLights, CausticOptions, CpuBudget, CpuHost, CpuPathOptions, CpuProgressiveOptions, DielectricBoundary, DielectricOptions,
+ DirectionalLightOptions, DirectionalLights, ImageHost, ImageRequest, Integrator, JobId, JobOptions, OutputOptions, Phase,
+ PunctualLightOptions, PunctualLights, RaytraceEnvironmentOptions, RaytraceOptions, RectangleLightOptions, SpotConeOptions, StudioLighting,
+ },
+ surface::{OpaqueSurface, unit_direction},
+ transmission::{Transmission, subsurface::Subsurface},
+};
+use std::{error::Error, fs, path::Path, sync::Arc, time::Duration};
+
+type Result<T> = std::result::Result<T, Box<dyn Error>>;
+const CASES: &[&str] = &[
+ "clear",
+ "tinted",
+ "hollow",
+ "nested",
+ "sheet",
+ "rough",
+ "dispersion",
+ "film",
+ "rough_sheet",
+ "caustics",
+ "rough_lights",
+ "rough_sheet_lights",
+ "rough_caustics",
+ "scattering_caustics",
+];
+const ENVIRONMENT: [f64; 3] = [0.7, 0.8, 1.0];
+const LIGHT: AreaLight = AreaLight { center: [-22.0, -30.0, 28.0], u: [9.0, 0.0, 0.0], v: [0.0, 0.0, -13.0], radiance: [4.0, 4.0, 4.0] };
+
+fn quad(mesh: &mut Mesh, vertices: [u32; 4]) {
+ let [a, b, c, d] = vertices;
+ mesh.triangles.extend([[a, b, c], [a, c, d]]);
+ mesh.tri_face.extend([0, 0]);
+}
+
+fn rectangle(points: [Vec3; 4]) -> Mesh {
+ let mut mesh = Mesh { positions: points.to_vec(), ..Default::default() };
+ quad(&mut mesh, [0, 1, 2, 3]);
+ mesh
+}
+
+fn box_mesh(half: Vec3) -> Mesh {
+ let mut mesh = Mesh::default();
+ for z in [-half.z, half.z] {
+ mesh.positions.extend([
+ Vec3::new(-half.x, -half.y, z),
+ Vec3::new(half.x, -half.y, z),
+ Vec3::new(half.x, half.y, z),
+ Vec3::new(-half.x, half.y, z),
+ ]);
+ }
+ quad(&mut mesh, [0, 3, 2, 1]);
+ quad(&mut mesh, [4, 5, 6, 7]);
+ for i in 0..4 {
+ let next = (i + 1) % 4;
+ quad(&mut mesh, [i, next, next + 4, i + 4]);
+ }
+ mesh
+}
+
+fn cup_mesh() -> Mesh {
+ // One connected, outward shell with an open air cavity and a solid bottom.
+ // Shared coordinates are authored once; no welded or repaired seam is needed.
+ let mut mesh = Mesh::default();
+ for (half, z) in [(10.0, -10.0), (10.0, 10.0), (7.0, 10.0), (7.0, -7.0)] {
+ mesh.positions.extend([Vec3::new(-half, -half, z), Vec3::new(half, -half, z), Vec3::new(half, half, z), Vec3::new(-half, half, z)]);
+ }
+ quad(&mut mesh, [0, 3, 2, 1]);
+ quad(&mut mesh, [12, 13, 14, 15]);
+ for i in 0..4 {
+ let next = (i + 1) % 4;
+ quad(&mut mesh, [i, next, next + 4, i + 4]);
+ quad(&mut mesh, [i + 4, next + 4, next + 8, i + 8]);
+ quad(&mut mesh, [next + 12, i + 12, i + 8, next + 8]);
+ }
+ mesh
+}
+
+fn prism_mesh() -> Mesh {
+ let mut mesh = Mesh {
+ positions: vec![
+ Vec3::new(-10.0, -8.0, -10.0),
+ Vec3::new(10.0, -8.0, -10.0),
+ Vec3::new(-10.0, 8.0, -10.0),
+ Vec3::new(-10.0, -8.0, 10.0),
+ Vec3::new(10.0, -8.0, 10.0),
+ Vec3::new(-10.0, 8.0, 10.0),
+ ],
+ triangles: vec![[0, 2, 1], [3, 4, 5]],
+ tri_face: vec![0; 2],
+ ..Default::default()
+ };
+ for face in [[0, 1, 4, 3], [1, 2, 5, 4], [2, 0, 3, 5]] {
+ quad(&mut mesh, face);
+ }
+ mesh
+}
+
+fn sphere_mesh() -> Mesh {
+ use std::f64::consts::{PI, TAU};
+ const SEGMENTS: u32 = 32;
+ const RINGS: u32 = 15;
+ let mut mesh = Mesh { positions: vec![Vec3::new(0.0, 0.0, -10.0)], ..Default::default() };
+ for ring in 1..=RINGS {
+ let latitude = -PI * 0.5 + PI * f64::from(ring) / f64::from(RINGS + 1);
+ for sector in 0..SEGMENTS {
+ let angle = TAU * f64::from(sector) / f64::from(SEGMENTS);
+ mesh.positions.push(Vec3::new(10.0 * latitude.cos() * angle.cos(), 10.0 * latitude.cos() * angle.sin(), 10.0 * latitude.sin()));
+ }
+ }
+ let top = 1 + RINGS * SEGMENTS;
+ mesh.positions.push(Vec3::new(0.0, 0.0, 10.0));
+ for sector in 0..SEGMENTS {
+ let next = (sector + 1) % SEGMENTS;
+ mesh.triangles.push([0, 1 + next, 1 + sector]);
+ mesh.triangles.push([top, 1 + (RINGS - 1) * SEGMENTS + sector, 1 + (RINGS - 1) * SEGMENTS + next]);
+ }
+ for ring in 0..RINGS - 1 {
+ for sector in 0..SEGMENTS {
+ let next = (sector + 1) % SEGMENTS;
+ let a = 1 + ring * SEGMENTS + sector;
+ let b = 1 + ring * SEGMENTS + next;
+ quad(&mut mesh, [a, b, b + SEGMENTS, a + SEGMENTS]);
+ }
+ }
+ mesh.tri_face.resize(mesh.triangles.len(), 0);
+ mesh
+}
+
+fn flat_mesh(source: Mesh) -> Result<Mesh> {
+ let count = source.triangles.len().checked_mul(3).ok_or("fixture vertex count overflow")?;
+ let mut mesh = Mesh::default();
+ mesh.positions.try_reserve_exact(count)?;
+ mesh.normals.try_reserve_exact(count)?;
+ mesh.triangles.try_reserve_exact(source.triangles.len())?;
+ mesh.tri_face.try_reserve_exact(source.triangles.len())?;
+ for (face, &[a, b, c]) in source.triangles.iter().enumerate() {
+ let point = |index: u32| source.positions.get(index as usize).copied().ok_or("fixture vertex index is invalid");
+ let [a, b, c] = [point(a)?, point(b)?, point(c)?];
+ let normal = unit_direction((b - a).cross(c - a))?;
+ let begin = u32::try_from(mesh.positions.len())?;
+ mesh.positions.extend([a, b, c]);
+ mesh.normals.extend([normal; 3]);
+ mesh.triangles.push([begin, begin + 1, begin + 2]);
+ mesh.tri_face.push(source.tri_face.get(face).copied().ok_or("fixture face ID is missing")?);
+ }
+ Ok(mesh)
+}
+
+fn body(name: &str, mesh: Mesh, color: Vec3, ior: f64, transmission: Option<Transmission>) -> Result<ProductMesh> {
+ Ok(ProductMesh {
+ name: name.into(),
+ mesh: Arc::new(flat_mesh(mesh)?),
+ color: [255, 255, 255],
+ opacity: 1.0,
+ surface: Some(OpaqueSurface::new(color, 0.0, 0.45, ior)?),
+ transmission,
+ faces: Vec::new(),
+ })
+}
+
+fn scene(case: &str) -> Result<ProductScene> {
+ let mut meshes = Vec::new();
+ let sigma = if ["tinted", "hollow", "nested", "sheet"].contains(&case) { Vec3::new(0.065, 0.012, 0.003) } else { Vec3::ZERO };
+ let sheet = ["sheet", "rough_sheet", "rough_sheet_lights"].contains(&case).then_some(3.0);
+ let mut transmission = Transmission::new(sigma, sheet)?;
+ let model = match case {
+ "rough" | "rough_sheet" | "rough_lights" | "rough_sheet_lights" => Some(GlassModel { roughness: 0.35, ..Default::default() }),
+ "rough_caustics" => Some(GlassModel { roughness: 0.2, ..Default::default() }),
+ "dispersion" => Some(GlassModel { dispersion: Some(Dispersion { abbe_number: 15.0 }), ..Default::default() }),
+ "film" => Some(GlassModel { thin_film: Some(ThinFilm { ior: 1.35, thickness_nm: 400.0 }), ..Default::default() }),
+ _ => None,
+ };
+ if let Some(model) = model {
+ transmission = transmission.with_shadow_transmission(false).with_model(model)?;
+ }
+ if case == "scattering_caustics" {
+ transmission = transmission.with_subsurface(Subsurface { scattering_per_mm: 0.06, anisotropy: 0.35 })?;
+ }
+ let optical_mesh = match case {
+ "hollow" => cup_mesh(),
+ "dispersion" => prism_mesh(),
+ "caustics" | "rough_caustics" => sphere_mesh(),
+ "sheet" | "rough_sheet" | "rough_sheet_lights" => {
+ rectangle([Vec3::new(-10.0, -1.0, -10.0), Vec3::new(10.0, -1.0, -10.0), Vec3::new(10.0, -1.0, 10.0), Vec3::new(-10.0, -1.0, 10.0)])
+ }
+ _ => box_mesh(Vec3::new(10.0, 8.0, 10.0)),
+ };
+ meshes.push(body("Original Glass boundary", optical_mesh, Vec3::ZERO, 1.5, Some(transmission))?);
+ if case == "nested" {
+ meshes.push(body(
+ "Original enclosed air bubble",
+ box_mesh(Vec3::new(6.0, 4.0, 6.0)),
+ Vec3::ZERO,
+ 1.0,
+ Some(Transmission::new(Vec3::ZERO, None)?),
+ )?);
+ }
+ for row in 0..6 {
+ for column in 0..8 {
+ let x = (f64::from(column) - 4.0) * 8.0;
+ let z = (f64::from(row) - 3.0) * 8.0;
+ let color = if (row + column) % 2 == 0 { Vec3::new(0.055, 0.08, 0.13) } else { Vec3::new(0.8, 0.65, 0.38) };
+ let mesh =
+ rectangle([Vec3::new(x, 18.0, z), Vec3::new(x + 8.0, 18.0, z), Vec3::new(x + 8.0, 18.0, z + 8.0), Vec3::new(x, 18.0, z + 8.0)]);
+ meshes.push(body(&format!("Original checker {column} {row}"), mesh, color, 1.5, None)?);
+ }
+ }
+ let floor = if ["caustics", "rough_caustics"].contains(&case) { -15.0 } else { -12.0 };
+ meshes.push(body(
+ "Original opaque floor",
+ rectangle([Vec3::new(-45.0, -35.0, floor), Vec3::new(45.0, -35.0, floor), Vec3::new(45.0, 35.0, floor), Vec3::new(-45.0, 35.0, floor)]),
+ Vec3::new(0.33, 0.37, 0.43),
+ 1.5,
+ None,
+ )?);
+ let bounds = meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds()));
+ Ok(ProductScene { meshes, bounds })
+}
+
+fn camera() -> Camera {
+ Camera { target: Vec3::ZERO, yaw: -0.23, pitch: 0.25, distance: 82.0, fov: 0.65, ..Default::default() }
+}
+
+fn caustics(case: &str) -> Option<CausticOptions> {
+ ["caustics", "rough_caustics", "scattering_caustics"].contains(&case).then_some(CausticOptions {
+ photons: 65536,
+ radius_mm: if case == "scattering_caustics" { 2.0 } else { 0.75 },
+ ..Default::default()
+ })
+}
+fn hard_only(case: &str) -> bool {
+ ["rough_lights", "rough_sheet_lights", "rough_caustics", "scattering_caustics"].contains(&case)
+}
+fn environment(case: &str) -> [f64; 3] {
+ if hard_only(case) { [0.0; 3] } else { ENVIRONMENT }
+}
+fn area_lights(case: &str) -> Vec<AreaLight> {
+ if hard_only(case) { Vec::new() } else { vec![LIGHT] }
+}
+fn directional(case: &str) -> Vec<DirectionalLightOptions> {
+ if ["rough_lights", "rough_sheet_lights"].contains(&case) {
+ vec![DirectionalLightOptions { direction: [0.15, -1.0, 0.25], color: [0.5, 0.7, 1.0], intensity: 3.0 }]
+ } else if caustics(case).is_some() {
+ vec![DirectionalLightOptions { direction: [0.2, -0.3, 1.0], color: [1.0; 3], intensity: 4.0 }]
+ } else {
+ Vec::new()
+ }
+}
+fn punctual(case: &str) -> Vec<PunctualLightOptions> {
+ if !["rough_lights", "rough_sheet_lights"].contains(&case) {
+ return Vec::new();
+ }
+ vec![
+ PunctualLightOptions {
+ position_mm: [-12.0, -30.0, 15.0],
+ color: [1.0, 0.3, 0.1],
+ intensity: 2.0,
+ reference_distance_mm: 30.0,
+ minimum_distance_mm: 0.1,
+ cone: None,
+ },
+ PunctualLightOptions {
+ position_mm: [20.0, -25.0, 18.0],
+ color: [0.2, 1.0, 0.3],
+ intensity: 2.0,
+ reference_distance_mm: 30.0,
+ minimum_distance_mm: 0.1,
+ cone: Some(SpotConeOptions { emitted_axis: [-20.0, 25.0, -18.0], inner_half_angle_radians: 0.25, outer_half_angle_radians: 0.65 }),
+ },
+ ]
+}
+fn request(scene: &ProductScene, cpu: bool, case: &str, samples: u32, width: u32) -> Result<ImageRequest> {
+ let raytrace = if cpu {
+ let mut dielectrics = Vec::new();
+ for (body_index, body) in scene.meshes.iter().enumerate() {
+ if let Some(optics) = body.transmission {
+ let surface = body.surface.ok_or("Glass body lacks its optical IOR")?;
+ let sigma = optics.extinction();
+ dielectrics.push(DielectricOptions {
+ model: optics.model(),
+ body_index,
+ body_name: body.name.clone(),
+ boundary: if optics.thin_wall_thickness_mm().is_some() { DielectricBoundary::ThinSheet } else { DielectricBoundary::ClosedMesh },
+ ior: surface.dielectric_ior(),
+ absorption_per_mm: [sigma.x, sigma.y, sigma.z],
+ thickness_mm: optics.thin_wall_thickness_mm().unwrap_or(0.0),
+ shadow_transmission: optics.shadow_transmission(),
+ subsurface: optics.subsurface(),
+ });
+ }
+ }
+ let areas = area_lights(case);
+ Some(RaytraceOptions {
+ caustics: caustics(case),
+ budget: CpuBudget::Studio,
+ progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 81 }),
+ path: Some(CpuPathOptions { max_depth: 16 }),
+ dielectrics,
+ environment: Some(RaytraceEnvironmentOptions { color: environment(case), intensity: 1.0 }),
+ lights: Some(directional(case)),
+ punctual_lights: Some(punctual(case)),
+ area_lights: Some(
+ areas
+ .iter()
+ .map(|light| RectangleLightOptions {
+ center_mm: light.center,
+ edge_u_mm: light.u.map(|v| v * 2.0),
+ edge_v_mm: light.v.map(|v| v * 2.0),
+ color: [1.0; 3],
+ intensity: 4.0,
+ })
+ .collect(),
+ ),
+ area_samples: (!areas.is_empty()).then_some(4),
+ output: Some(Box::new(OutputOptions { linear_exr: true, ..Default::default() })),
+ ..Default::default()
+ })
+ } else {
+ None
+ };
+ let mut camera = camera();
+ if ["caustics", "rough_caustics"].contains(&case) {
+ camera.pitch = 0.65;
+ camera.target.z = -4.0;
+ }
+ Ok(ImageRequest {
+ camera,
+ width,
+ height: width * 3 / 4,
+ background: [228, 235, 245],
+ transparent_background: false,
+ integrator: if cpu { Integrator::Raytrace } else { Integrator::Raster },
+ raytrace,
+ studio_weights: None,
+ environment: None,
+ textures: None,
+ })
+}
+
+struct Evidence<'a> {
+ samples: u32,
+ width: u32,
+ out: &'a Path,
+}
+
+fn render(host: &ImageHost, source: ProductScene, cpu: bool, case: &str, evidence: &Evidence<'_>, serial: u64) -> Result<()> {
+ let Evidence { samples, width, out } = *evidence;
+ let backend = if cpu { "cpu" } else { "gpu" };
+ let request = request(&source, cpu, case, samples, width)?;
+ let options = if cpu {
+ JobOptions::default()
+ } else {
+ JobOptions {
+ caustics: caustics(case),
+ samples,
+ seed: 81,
+ max_depth: 16,
+ nested_media: case == "nested",
+ linear_exr: true,
+ lighting: Some(StudioLighting {
+ directional_lights: DirectionalLights::new(&directional(case))?,
+ punctual_lights: PunctualLights::new(&punctual(case))?,
+ environment: environment(case),
+ area_lights: AreaLights::new(&area_lights(case))?,
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ };
+ let descriptor = host.descriptor_for_request(&request)?;
+ let recorded_request = serde_json::to_value(&request)?;
+ let recorded_options = serde_json::to_value(options)?;
+ let geometry: Vec<_> = source
+ .meshes
+ .iter()
+ .map(|body| {
+ json!({
+ "name":body.name,"positions":body.mesh.positions,"normals":body.mesh.normals,
+ "triangles":body.mesh.triangles,"tri_face":body.mesh.tri_face,"preview_color":body.color,"opacity":body.opacity,
+ "surface":body.surface.map(|surface|json!({
+ "base_color_linear":surface.base_color(),"metallic":surface.metallic(),"roughness":surface.roughness(),
+ "ior":surface.dielectric_ior(),"clear_coat_present":surface.clear_coat().is_some()
+ })),
+ "transmission":body.transmission.map(|optics|json!({
+ "absorption_per_mm":optics.extinction(),"thin_wall_thickness_mm":optics.thin_wall_thickness_mm(),
+ "shadow_transmission":optics.shadow_transmission(),"subsurface":optics.subsurface(),"model":optics.model()
+ }))
+ })
+ })
+ .collect();
+ let mut source = source;
+ if cpu {
+ // CPU optics were lowered into RaytraceOptions above. Its capture scene
+ // carries opaque geometry; scene-level Transmission belongs to GPU.
+ for body in &mut source.meshes {
+ body.transmission = None;
+ for face in &mut body.faces {
+ face.transmission = None;
+ }
+ }
+ }
+ let handle = host.submit_with_options(JobId { session: 20261104, serial, generation: 1 }, 1, source, request, options)?;
+ let status = match handle.wait_timeout(Duration::from_secs(600)) {
+ Ok(status) => status,
+ Err(error) => {
+ let _ = handle.cancel();
+ return Err(error.into());
+ }
+ };
+ if status.progress.phase != Phase::Completed {
+ return Err(format!("{backend} {case} failed: {:?}", status.error).into());
+ }
+ let frame = handle.frame()?.ok_or("completed render has no frame")?;
+ let png = image::load_from_memory(frame.png())?.to_rgba8();
+ if png.dimensions() != (width, width * 3 / 4) || !png.pixels().any(|pixel| pixel.0 != [228, 235, 245, 255]) {
+ return Err("render did not produce the original Glass fixture".into());
+ }
+ let exr = frame.linear_exr().ok_or("completed render has no raw EXR master")?;
+ fs::write(out.join(format!("{backend}-{case}.png")), frame.png())?;
+ fs::write(out.join(format!("{backend}-{case}.exr")), exr)?;
+ let receipt = json!({
+ "status":"PASS", "case":case,"backend":backend,"executor":descriptor,"request":recorded_request,"options":recorded_options,
+ "frame":frame.info,"linear_master":frame.linear_master_info(),"original_geometry":geometry,
+ "qualification":"headless completed image and retained same-frame raw master only",
+ "application_ui_tested":false,"saved_design_tested":false,"image_quality_acceptance":false,
+ "pixel_identity_between_backends_expected":false,
+ "sampling_difference":"CPU uses four samples per enabled area connection; GPU uses its native estimator. Camera and branch sample streams differ."
+ });
+ fs::write(out.join(format!("{backend}-{case}.json")), serde_json::to_vec_pretty(&receipt)?)?;
+ println!("Completed {backend} {case}: {width}x{}, {samples} samples/pixel", width * 3 / 4);
+ Ok(())
+}
+
+fn main() -> Result<()> {
+ let mut args = std::env::args().skip(1);
+ let out = args.next().ok_or("usage: glass_comparison NEW_OUTPUT_DIRECTORY [cpu|gpu|both] [SPP=32] [CASE=all] [WIDTH=256]")?;
+ let backend = args.next().unwrap_or_else(|| "both".into());
+ let samples = args.next().map_or(Ok(32), |v| v.parse::<u32>())?;
+ let case = args.next().unwrap_or_else(|| "all".into());
+ let width = args.next().map_or(Ok(256), |v| v.parse::<u32>())?;
+ if args.next().is_some() || !["cpu", "gpu", "both"].contains(&backend.as_str()) || !(1..=64).contains(&samples) || !(64..=1024).contains(&width) {
+ return Err("expected cpu|gpu|both, 1..64 SPP and width 64..1024".into());
+ }
+ if case != "all" && !CASES.contains(&case.as_str()) {
+ return Err(format!("case must be one of {} or all", CASES.join("|")).into());
+ }
+ let out = Path::new(&out);
+ fs::create_dir(out)?;
+ let evidence = Evidence { samples, width, out };
+ let cpu = (backend != "gpu").then(CpuHost::for_platform).transpose()?;
+ let gpu = (backend != "cpu").then(solidcraft_gpu::path::host).transpose()?;
+ for (index, selected) in CASES.iter().copied().enumerate().filter(|(_, selected)| case == "all" || case == *selected) {
+ let serial = u64::try_from(index)? + 1;
+ if let Some(host) = &cpu {
+ render(host, scene(selected)?, true, selected, &evidence, serial)?;
+ }
+ if let Some(host) = &gpu {
+ render(host, scene(selected)?, false, selected, &evidence, serial)?;
+ }
+ }
+ Ok(())
+}
diff --git a/crates/gpu/src/path/glass.wgsl b/crates/gpu/src/path/glass.wgsl
new file mode 100644
index 0000000000..9d3f77fd92
--- /dev/null
+++ b/crates/gpu/src/path/glass.wgsl
@@ -0,0 +1,186 @@
+// Optional dielectric extensions. Legacy materials do not execute these draws
+// or allocate their extra packed material lane.
+var<private> transport_wavelength: f32=0.0;
+var<private> transport_medium_id: f32=0.0;
+var<private> transport_medium_ior: f32=1.0;
+var<private> transport_medium_sigma: vec3<f32>=vec3<f32>(0.0);
+var<private> transport_medium_scatter: f32=0.0;
+var<private> transport_source_triangle: u32=0xffffffffu;
+var<private> transport_connection_origin: vec3<f32>=vec3<f32>(0.0);
+var<private> transport_connection_origin_low: vec3<f32>=vec3<f32>(0.0);
+var<private> transport_boundary_connection: bool=false;
+fn glass_wavelength(channel: u32) -> f32 {
+ return array<f32,3>(610.0,550.0,460.0)[channel];
+}
+fn glass_ior(base: f32, abbe: f32, wavelength: f32) -> f32 {
+ if abbe<=0.0 || wavelength<=0.0 {return base;}
+ let f=486.1327;let c=656.2725;let d=587.5618;
+ let b=((base-1.0)/abbe)/(1.0/(f*f)-1.0/(c*c));
+ return base+b*(1.0/(wavelength*wavelength)-1.0/(d*d));
+}
+fn glass_cmul(a: vec2<f32>, b: vec2<f32>) -> vec2<f32> {
+ return vec2<f32>(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);
+}
+fn glass_cdiv(a: vec2<f32>, b: vec2<f32>) -> vec2<f32> {
+ return vec2<f32>(dot(a,b),a.y*b.x-a.x*b.y)/dot(b,b);
+}
+fn glass_complex_cosine(incident_sine_squared: f32, ni: f32, nt: f32) -> vec2<f32> {
+ let square=1.0-(ni/nt)*(ni/nt)*incident_sine_squared;
+ return vec2<f32>(sqrt(max(square,0.0)),sqrt(max(-square,0.0)));
+}
+// Lossless coherent single film between the actual incident and transmitted
+// media. Complex admittances retain evanescent waves and frustrated film TIR.
+fn glass_film_polarization(cosine: f32, ni: f32, nt: f32, nf: f32, thickness: f32, wavelength: f32, p: bool) -> f32 {
+ let sin2=max(0.0,1.0-cosine*cosine);
+ let cf=glass_complex_cosine(sin2,ni,nf);
+ let ct=glass_complex_cosine(sin2,ni,nt);
+ let q0=vec2<f32>(select(ni*cosine,cosine/ni,p),0.0);
+ let qf=cf*select(nf,1.0/nf,p);
+ let qt=ct*select(nt,1.0/nt,p);
+ let phase=cf*(2.0*PI*nf*thickness/wavelength);
+ var numerator=vec2<f32>(0.0);var denominator=vec2<f32>(0.0);
+ if dot(phase,phase)<0.0001 {
+ // Characteristic-matrix limit avoids Airy's cancellation/0÷0 at the
+ // film critical angle. sin(phase)/qf has a finite analytic limit.
+ let phase2=glass_cmul(phase,phase);
+ let phase4=glass_cmul(phase2,phase2);
+ let cosine_phase=vec2<f32>(1.0,0.0)-phase2*0.5+phase4/24.0;
+ let sinc=vec2<f32>(1.0,0.0)-phase2/6.0+phase4/120.0;
+ let ratio=sinc*(2.0*PI*thickness/wavelength*select(1.0,nf*nf,p));
+ let a=cosine_phase+glass_cmul(vec2<f32>(-ratio.y,ratio.x),qt);
+ let qsin=glass_cmul(qf,glass_cmul(phase,sinc));
+ let b=vec2<f32>(-qsin.y,qsin.x)+glass_cmul(cosine_phase,qt);
+ numerator=glass_cmul(q0,a)-b;denominator=glass_cmul(q0,a)+b;
+ } else {
+ let r01=glass_cdiv(q0-qf,q0+qf);
+ let r12=glass_cdiv(qf-qt,qf+qt);
+ // This decaying form stays finite for thick evanescent films.
+ let wave=exp(-2.0*phase.y)*vec2<f32>(cos(2.0*phase.x),sin(2.0*phase.x));
+ let delayed=glass_cmul(r12,wave);
+ numerator=r01+delayed;denominator=vec2<f32>(1.0,0.0)+glass_cmul(r01,delayed);
+ }
+ let reflected=glass_cdiv(numerator,denominator);
+ return clamp(dot(reflected,reflected),0.0,1.0);
+}
+fn glass_film(cosine: f32, ni: f32, nt: f32, nf: f32, thickness: f32, wavelength: f32) -> vec2<f32> {
+ let bare=dielectric(cosine,ni,nt);
+ if thickness<=0.0 || nf==ni || nf==nt {return bare.xy;}
+ if bare.z<0.0 {return vec2<f32>(1.0);}
+ if cosine==0.0 {
+ if ni!=nt || ni!=nf {return vec2<f32>(1.0);}
+ return vec2<f32>(0.0);
+ }
+ return vec2<f32>(glass_film_polarization(cosine,ni,nt,nf,thickness,wavelength,false),glass_film_polarization(cosine,ni,nt,nf,thickness,wavelength,true));
+}
+fn glass_reflection(t: Triangle, cosine: f32, ni: f32, nt: f32, wavelength: f32) -> vec3<f32> {
+ let bare=dielectric(cosine,ni,nt);
+ if t.glass.z<=0.0 {return vec3<f32>((bare.x+bare.y)*0.5);}
+ if wavelength>0.0 {
+ let f=glass_film(cosine,ni,nt,t.glass.w,t.glass.z,wavelength);
+ return vec3<f32>((f.x+f.y)*0.5);
+ }
+ var result=vec3<f32>(0.0);
+ for(var channel=0u;channel<3u;channel+=1u) {
+ let f=glass_film(cosine,ni,nt,t.glass.w,t.glass.z,glass_wavelength(channel));
+ result[channel]=(f.x+f.y)*0.5;
+ }
+ return result;
+}
+fn glass_sheet(t: Triangle, f: vec3<f32>, cosine: f32, ni: f32, nt: f32, wavelength: f32) -> Sheet {
+ if t.glass.z<=0.0 {return sheet(t,f);}
+ if f.z<0.0 {return Sheet(vec3<f32>(1.0),vec3<f32>(0.0));}
+ var attenuation=vec3<f32>(1.0);
+ if t.parameters.w>0.0 {
+ if f.z==0.0 {atomicOr(&failures[7],2u);return Sheet(vec3<f32>(0.0),vec3<f32>(0.0));}
+ attenuation=exp(-t.optics.xyz*(t.parameters.w/f.z));
+ }
+ var result=Sheet(vec3<f32>(0.0),vec3<f32>(0.0));
+ for(var channel=0u;channel<3u;channel+=1u) {
+ let lambda=select(glass_wavelength(channel),wavelength,wavelength>0.0);
+ let coated=glass_film(cosine,ni,nt,t.glass.w,t.glass.z,lambda);
+ let s=sheet_polarization(coated.x,attenuation);
+ let p=sheet_polarization(coated.y,attenuation);
+ result.reflection[channel]=(s.reflection[channel]+p.reflection[channel])*0.5;
+ result.transmission[channel]=(s.transmission[channel]+p.transmission[channel])*0.5;
+ }
+ return result;
+}
+fn glass_smith_weight(nv: f32, nl: f32, alpha: f32) -> f32 {
+ let cv=abs(nv);let cl=abs(nl);
+ if cv<=0.0 || cl<=0.0 {return 0.0;}
+ let sv=sqrt(cv*cv+alpha*alpha*max(0.0,1.0-cv*cv));
+ let sl=sqrt(cl*cl+alpha*alpha*max(0.0,1.0-cl*cl));
+ // Height-correlated G2/G1 without squared tangent division or inf/inf.
+ if cv>=cl {let ratio=cl/cv;return ratio*(cv+sv)/(sv*ratio+sl);}
+ return (cv+sv)/(sv+sl*(cv/cl));
+}
+fn glass_visible_normal(n: vec3<f32>, view: vec3<f32>, alpha: f32, variates: vec2<f32>) -> vec3<f32> {
+ let axis=select(vec3<f32>(0.0,0.0,1.0),vec3<f32>(1.0,0.0,0.0),abs(n.z)>=0.9);
+ let x=unit(cross(axis,n));let y=cross(n,x);
+ let v=vec3<f32>(dot(view,x),dot(view,y),dot(view,n));
+ let stretched=unit(vec3<f32>(alpha*v.xy,v.z));
+ let length_squared=dot(stretched.xy,stretched.xy);
+ var t1=vec3<f32>(1.0,0.0,0.0);
+ if length_squared>0.0 {t1=vec3<f32>(-stretched.y,stretched.x,0.0)/sqrt(length_squared);}
+ let t2=cross(stretched,t1);
+ let radius=sqrt(variates.x);let phi=2.0*PI*variates.y;
+ let a=radius*cos(phi);var b=radius*sin(phi);
+ let s=(1.0+stretched.z)*0.5;
+ b=(1.0-s)*sqrt(max(0.0,1.0-a*a))+s*b;
+ let normal=a*t1+b*t2+sqrt(max(0.0,1.0-a*a-b*b))*stretched;
+ let h=unit(vec3<f32>(alpha*normal.xy,max(0.0,normal.z)));
+ return unit(x*h.x+y*h.y+n*h.z);
+}
+struct GlassEvent {direction:vec3<f32>,weight:vec3<f32>,transmitted:bool,valid:bool};
+fn glass_rough_active(t:Triangle,ni:f32,nt:f32)->bool {
+ return t.glass.x>0.0 && !(ni==nt && (t.glass.z<=0.0 || t.glass.w==ni));
+}
+fn glass_macro_normal(incident:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,ni:f32,nt:f32)->vec3<f32> {
+ if glass_geometric_normals() {return geometric;}
+ let f=dielectric(clamp(dot(normal,-incident),0.0,1.0),ni,nt);
+ let transmitted=refract(incident,normal,ni/nt);
+ if (f.z>=0.0 && dot(transmitted,geometric)>=0.0) || dot(reflect(incident,normal),geometric)<=0.0 {return geometric;}
+ return normal;
+}
+fn glass_interface(t:Triangle,incident:vec3<f32>,macro_normal:vec3<f32>,geometric:vec3<f32>,ni:f32,nt:f32,wavelength:f32,radiance:bool,stratum:u32,strata:u32,rng:ptr<function,u32>) -> GlassEvent {
+ var normal=macro_normal;
+ let rough=glass_rough_active(t,ni,nt);
+ if rough && dot(macro_normal,-incident)<=0.0 {return GlassEvent(incident,vec3<f32>(0.0),false,false);}
+ if rough {normal=glass_visible_normal(macro_normal,-incident,t.glass.x*t.glass.x,vec2<f32>(random(rng),random(rng)));}
+ let f=dielectric(clamp(dot(normal,-incident),0.0,1.0),ni,nt);
+ let reflection=glass_reflection(t,clamp(dot(normal,-incident),0.0,1.0),ni,nt,wavelength);
+ let probability=dot(reflection,vec3<f32>(1.0/3.0));
+ var branch=random(rng);
+ if strata>1u {branch=(f32(stratum)+branch)/f32(strata);*rng^=(stratum+1u)*0x85ebca6bu;}
+ let reflected=branch<probability;
+ var outgoing=reflect(incident,normal);var weight=vec3<f32>(0.0);
+ if reflected {
+ if dot(outgoing,geometric)<=0.0 {return GlassEvent(outgoing,weight,false,false);}
+ weight=reflection/probability;
+ } else {
+ outgoing=unit(refract(incident,normal,ni/nt));
+ if f.z<0.0 || dot(outgoing,geometric)>=0.0 {return GlassEvent(outgoing,weight,true,false);}
+ weight=(vec3<f32>(1.0)-reflection)/(1.0-probability);
+ if radiance {weight*=(ni/nt)*(ni/nt);}
+ }
+ if rough {weight*=glass_smith_weight(dot(macro_normal,-incident),dot(macro_normal,outgoing),t.glass.x*t.glass.x);}
+ return GlassEvent(outgoing,weight,!reflected,true);
+}
+struct GlassSheetWalk {direction:vec3<f32>,weight:vec3<f32>,consumed:u32,valid:bool};
+fn glass_rough_sheet(t:Triangle,incident:vec3<f32>,normal:vec3<f32>,outside:f32,inside:f32,wavelength:f32,radiance:bool,remaining:u32,stratum:u32,strata:u32,rng:ptr<function,u32>) -> GlassSheetWalk {
+ var direction=incident;var weight=vec3<f32>(1.0);var internal=false;
+ for(var event=0u;event<remaining;event+=1u) {
+ let macro_normal=select(-normal,normal,dot(direction,normal)<0.0);
+ let ni=select(outside,inside,internal);let nt=select(inside,outside,internal);
+ let sampled=glass_interface(t,direction,macro_normal,macro_normal,ni,nt,wavelength,radiance,stratum,select(1u,strata,event==0u),rng);
+ if !sampled.valid {return GlassSheetWalk(sampled.direction,vec3<f32>(0.0),event+1u,false);}
+ direction=sampled.direction;weight*=sampled.weight;
+ if (!internal && !sampled.transmitted) || (internal && sampled.transmitted) {return GlassSheetWalk(direction,weight,event+1u,true);}
+ internal=true;
+ let cosine=abs(dot(direction,normal));
+ if cosine==0.0 {return GlassSheetWalk(direction,vec3<f32>(0.0),event+1u,false);}
+ if t.parameters.w>0.0 {weight*=exp(-t.optics.xyz*(t.parameters.w/cosine));}
+ if !any(weight>vec3<f32>(0.0)) {return GlassSheetWalk(direction,weight,event+1u,false);}
+ }
+ return GlassSheetWalk(direction,vec3<f32>(0.0),remaining,false);
+}
diff --git a/crates/gpu/src/path/glass_lighting.wgsl b/crates/gpu/src/path/glass_lighting.wgsl
new file mode 100644
index 0000000000..8cc49efe06
--- /dev/null
+++ b/crates/gpu/src/path/glass_lighting.wgsl
@@ -0,0 +1,232 @@
+// Legacy pipelines specialize this entire optical-lighting arc away. The lazy
+// rough/HG pipeline uses the same six storage buffers as ordinary images.
+override GLASS_DELTA_LIGHTS: bool=false;
+// Bit zero of the aligned material offset marks a non-identity optical model.
+// HG alone needs delta-light connections while keeping smooth shading normals.
+fn glass_geometric_normals()->bool {return u.volume_albedo.w>0.0 || photon_enabled();}
+fn glass_vacuum()->Medium {return Medium(0.0,1.0,vec3<f32>(0.0),vec2<f32>(0.0));}
+fn glass_set_medium(m:Medium) {
+ transport_medium_id=m.id;transport_medium_ior=m.ior;
+ transport_medium_sigma=m.sigma;transport_medium_scatter=m.scatter.x;
+}
+fn glass_reflection_controls(model: vec4<f32>, cosine: f32, ni: f32, nt: f32, wavelength: f32) -> vec3<f32> {
+ let bare=dielectric(cosine,ni,nt);
+ if model.z<=0.0 {return vec3<f32>((bare.x+bare.y)*0.5);}
+ if wavelength>0.0 {
+ let f=glass_film(cosine,ni,nt,model.w,model.z,wavelength);
+ return vec3<f32>((f.x+f.y)*0.5);
+ }
+ var result=vec3<f32>(0.0);
+ for(var channel=0u;channel<3u;channel+=1u) {
+ let f=glass_film(cosine,ni,nt,model.w,model.z,glass_wavelength(channel));
+ result[channel]=(f.x+f.y)*0.5;
+ }
+ return result;
+}
+// Positive arithmetic is checked before divisions/products can generate an
+// infinity. Invalid interface response is a scene precision refusal, distinct
+// from the existing policy that omits an unbounded punctual source sample.
+fn glass_response_product(a:f32,b:f32)->f32 {
+ if !(a>=0.0 && a<=3.4e38 && b>=0.0 && b<=3.4e38) || a>3.4e38/max(b,1.0) {atomicOr(&failures[7],16u);return 0.0;}
+ return a*b;
+}
+fn glass_response_ratio(numerator:f32,scale:f32,denominator:f32)->f32 {
+ if numerator==0.0 || scale==0.0 {return 0.0;}
+ if !(numerator>0.0 && numerator<=3.4e38 && scale>0.0 && scale<=3.4e38 && denominator>=1.17549435e-38 && denominator<=3.4e38) {atomicOr(&failures[7],16u);return 0.0;}
+ // Multiply a reducing factor first; divide by a reducing denominator first.
+ // Every rejected overflow would also overflow the complete positive ratio.
+ var value=numerator;
+ if scale<=1.0 {value*=scale;}
+ if value>3.4e38*min(denominator,1.0) {atomicOr(&failures[7],16u);return 0.0;}
+ value/=max(denominator,1.17549435e-38);
+ if scale>1.0 {value=glass_response_product(value,scale);}
+ return value;
+}
+fn glass_evaluate_cosine(model:vec4<f32>,incident:vec3<f32>,outgoing:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,ni:f32,nt:f32,wavelength:f32)->vec3<f32> {
+ let view=-incident;let cv=dot(view,normal);let cl=dot(outgoing,normal);
+ if !(model.x>0.0 && !(ni==nt && (model.z<=0.0 || model.w==ni))) || cv<=0.0 || cl==0.0 || cl*dot(outgoing,geometric)<=0.0 || (cl<0.0 && ni==nt) {return vec3<f32>(0.0);}
+ var sum=view+outgoing;
+ if cl<0.0 {sum=view*ni+outgoing*nt;}
+ if dot(sum,sum)==0.0 {return vec3<f32>(0.0);}
+ var facet=unit(sum);if dot(facet,normal)<0.0 {facet=-facet;}
+ let vm=dot(view,facet);let lm=dot(outgoing,facet);
+ if vm<=0.0 || (cl>0.0 && lm<=0.0) || (cl<0.0 && lm>=0.0) {return vec3<f32>(0.0);}
+ let alpha=model.x*model.x;let a2=alpha*alpha;
+ let cm=clamp(dot(facet,normal),0.0,1.0);
+ let sine=cross(facet,normal);
+ let denominator=dot(sine,sine)+a2*cm*cm;
+ let distribution_root=(alpha/denominator)/sqrt(PI);
+ let distribution=distribution_root*distribution_root;
+ let root=sqrt(cv*cv+a2*max(0.0,1.0-cv*cv));
+ let g2_over_cv=(2.0/(cv+root))*glass_smith_weight(cv,cl,alpha);
+ let fresnel=glass_reflection_controls(model,clamp(vm,0.0,1.0),ni,nt,wavelength);
+ var coefficient=fresnel;var scale=g2_over_cv*0.25;var divisor=1.0;
+ if cl<0.0 {
+ let jacobian_denominator=ni*vm+nt*lm;
+ if jacobian_denominator==0.0 {return vec3<f32>(0.0);}
+ coefficient=vec3<f32>(1.0)-fresnel;
+ scale=g2_over_cv*abs(vm*lm)*ni*ni;
+ divisor=jacobian_denominator*jacobian_denominator;
+ }
+ var response=vec3<f32>(0.0);
+ for(var channel=0u;channel<3u;channel+=1u) {response[channel]=glass_response_ratio(glass_response_product(coefficient[channel],distribution),scale,divisor);}
+ return response;
+}
+fn glass_hg_phase(cosine:f32,g:f32)->f32 {
+ let denominator=1.0+g*g-2.0*g*clamp(cosine,-1.0,1.0);
+ return (1.0-g*g)/(4.0*PI*denominator*sqrt(denominator));
+}
+fn glass_importance_normal(incident:vec3<f32>,outgoing:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>)->f32 {
+ let numerator=abs(dot(-incident,normal))*abs(dot(outgoing,geometric));
+ let denominator=abs(dot(-incident,geometric))*abs(dot(outgoing,normal));
+ if denominator==0.0 {return 0.0;}
+ let correction=numerator/denominator;
+ if !(correction>=0.0) || !(correction<=3.4e38) {atomicOr(&failures[7],1u);return 0.0;}
+ return correction;
+}
+// One uniformly retained hard-light vertex keeps native optical visibility at
+// one call site with96 bytes of private payload. For K<=16 eligible camera
+// vertices, K*prefix[J]*direct[J] estimates their complete sum. Selection uses
+// its own RNG, leaving transport draws unchanged. Null/depth exits retain the
+// estimator; multi-vertex map-off paths acquire additional sampling variance.
+// mode0 closed; mode1 HG; mode2 first sheet reflection; mode3 internal exit;
+// mode4 closed reflection only after an opaque straight-shadow replaced prefix.
+// Raw lanes avoid composite array copies across function pointers and preserve
+// point/prefix bits independently of floating-point optimization in the walk.
+fn glass_offer_light(lights:ptr<function,array<vec4<u32>,6>>,count:ptr<function,u32>,selection_rng:ptr<function,u32>,point:PrecisePoint,incident:vec3<f32>,prefix:vec3<f32>,ni:f32,nt:f32,source_triangle:u32,mode:u32,medium:Medium) {
+ let studio=u.environment.w>0.0;
+ if select(3u,u32(u.light_count.x)+u32(u.light_count.y),studio)==0u {return;}
+ let index=*count;
+ if index>=16u || index>=u.sampling.y {atomicOr(&failures[7],8u);return;}
+ *count=index+1u;
+ if index>0u && random(selection_rng)>=1.0/f32(index+1u) {return;}
+ (*lights)[0]=vec4<u32>(bitcast<vec3<u32>>(point.hi),source_triangle);
+ (*lights)[1]=vec4<u32>(bitcast<vec3<u32>>(point.lo),mode);
+ (*lights)[2]=bitcast<vec4<u32>>(vec4<f32>(incident,ni));
+ (*lights)[3]=bitcast<vec4<u32>>(vec4<f32>(prefix,nt));
+ (*lights)[4]=bitcast<vec4<u32>>(vec4<f32>(medium.sigma,medium.scatter.x));
+ (*lights)[5]=bitcast<vec4<u32>>(vec4<f32>(medium.id,medium.ior,medium.scatter.y,0.0));
+}
+// Eight vec4 lanes per path in one bounded dispatch tile. The first six
+// contain the selected request, then count/wavelength and the camera path value.
+// Film planes precede this scratch and retain their historical offsets. Integer
+// metadata uses exact numeric f32 encoding rather than subnormal bit patterns.
+fn glass_tile_address(pixel:u32)->u32 {
+ return u.image.x*u.image.y*select(1u,3u,u.adaptive_budget.x>0u)+(pixel-u.image.w)*8u;
+}
+fn glass_capture_light(lights:ptr<function,array<vec4<u32>,6>>,count:u32,wavelength:f32,pixel:u32) {
+ let address=glass_tile_address(pixel);
+ if count>0u {
+ for(var lane=0u;lane<6u;lane+=1u) {accumulation[address+lane]=bitcast<vec4<f32>>((*lights)[lane]);}
+ accumulation[address].w=f32(select((*lights)[0].w,0u,(*lights)[1].w==1u));accumulation[address+1u].w=f32((*lights)[1].w);
+ }
+ accumulation[address+6u]=vec4<f32>(f32(count),wavelength,0.0,0.0);
+}
+fn glass_resolve_light(lights:ptr<function,array<vec4<u32>,6>>,count:u32,wavelength:f32)->vec3<f32> {
+ if !GLASS_DELTA_LIGHTS || count==0u {return vec3<f32>(0.0);}
+ let point=(*lights)[0];let low=(*lights)[1];let mode=low.w;
+ let incident=bitcast<vec4<f32>>((*lights)[2]);let prefix=bitcast<vec4<f32>>((*lights)[3]);
+ let medium_sigma=bitcast<vec4<f32>>((*lights)[4]);let medium_other=bitcast<vec4<f32>>((*lights)[5]);
+ var model=vec4<f32>(0.0);var normal=vec3<f32>(0.0);var geometric=vec3<f32>(0.0);
+ var current=glass_vacuum();var next=glass_vacuum();var source_triangle=0xffffffffu;
+ var escape=0;
+ if mode==1u {
+ current=Medium(medium_other.x,medium_other.y,medium_sigma.xyz,vec2<f32>(medium_sigma.w,medium_other.z));
+ next=current;
+ } else {
+ source_triangle=point.w;let t=triangle(min(source_triangle,max(geometry[0],1u)-1u));model=t.glass;
+ let outward=unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
+ let entering=dot(outward,-incident.xyz)>=0.0;
+ geometric=select(-outward,outward,entering);normal=geometric;
+ if mode==0u || mode==4u {
+ var parent=glass_vacuum();
+ if t.interior.w>0.0 {
+ let p=triangle(max(u32(t.interior.w),1u)-1u);
+ parent=Medium(p.optics.w,glass_ior(p.parameters.z,p.glass.y,wavelength),p.optics.xyz,p.interior.xy);
+ }
+ let own=Medium(t.optics.w,glass_ior(t.parameters.z,t.glass.y,wavelength),t.optics.xyz,t.interior.xy);
+ current=own;next=parent;if entering {current=parent;next=own;}
+ current.ior=incident.w;next.ior=prefix.w;
+ if mode==4u {escape=1;}
+ } else {escape=select(1,-1,mode==3u);}
+ }
+ let physical=PrecisePoint(bitcast<vec3<f32>>(point.xyz),bitcast<vec3<f32>>(low.xyz));
+ let studio=u.environment.w>0.0;
+ let directions=select(3u,u32(u.light_count.x),studio);
+ let source_count=directions+select(0u,u32(u.light_count.y),studio);
+ var result=vec3<f32>(0.0);
+ let saved_id=transport_medium_id;let saved_ior=transport_medium_ior;
+ let saved_sigma=transport_medium_sigma;let saved_scatter=transport_medium_scatter;
+ let saved_source=transport_source_triangle;let saved_boundary=transport_boundary_connection;
+ let saved_origin=transport_connection_origin;let saved_low=transport_connection_origin_low;
+ transport_connection_origin=physical.hi;transport_connection_origin_low=physical.lo;
+ transport_source_triangle=source_triangle;transport_boundary_connection=mode!=1u;
+ for(var source=0u;source<source_count;source+=1u) {
+ var direction=FIXED_LIGHTS[min(source,2u)].xyz;
+ var radiance=vec3<f32>(FIXED_LIGHTS[min(source,2u)].w*u.lighting.z*u.studio_weights[min(source,2u)]);
+ var distance=FAR;
+ if source<directions {
+ if studio {let light=u.directional_lights[min(source,7u)];direction=light.direction.xyz;radiance=light.color.xyz*light.direction.w;}
+ } else {
+ let point_index=min(source-min(source,directions),7u);
+ let sample=punctual_sample(u.punctual_lights[point_index],physical);
+ if sample.omitted!=0u {continue;}
+ direction=sample.direction;radiance=sample.radiance;distance=sample.distance;
+ }
+ if !any(radiance>vec3<f32>(0.0)) {continue;}
+ var response=vec3<f32>(0.0);var connection_medium=current;
+ if mode==1u {response=vec3<f32>(glass_hg_phase(dot(incident.xyz,direction),current.scatter.y));}
+ else {
+ let cosine=dot(normal,direction);
+ if (escape==1 && cosine<=0.0) || (escape == -1 && cosine>=0.0) {continue;}
+ response=glass_evaluate_cosine(model,incident.xyz,direction,normal,geometric,incident.w,prefix.w,wavelength);
+ if cosine<0.0 {connection_medium=next;}
+ }
+ if !all(response>=vec3<f32>(0.0)) || !all(response<=vec3<f32>(3.4e38)) {atomicOr(&failures[7],16u);continue;}
+ if !any(response>vec3<f32>(0.0)) {continue;}
+ var contribution=vec3<f32>(0.0);
+ for(var channel=0u;channel<3u;channel+=1u) {contribution[channel]=glass_response_product(response[channel],radiance[channel]);}
+ glass_set_medium(connection_medium);
+ let endpoint=select(FAR,punctual_endpoint(distance),source>=directions);
+ if emitter_hit_precise(physical.hi,physical.lo,direction,0.0).distance<endpoint {continue;}
+ let visibility=shadow_transmittance(physical.hi,physical.lo,direction,endpoint,0.0);
+ let atmosphere=volume_transmittance_precise(physical.hi,physical.lo,direction,distance);
+ result+=contribution*visibility.transmittance*atmosphere;
+ }
+ transport_medium_id=saved_id;transport_medium_ior=saved_ior;
+ transport_medium_sigma=saved_sigma;transport_medium_scatter=saved_scatter;
+ transport_source_triangle=saved_source;transport_boundary_connection=saved_boundary;
+ transport_connection_origin=saved_origin;transport_connection_origin_low=saved_low;
+ return prefix.xyz*result*f32(count);
+}
+struct GlassRadiantSheet {walk:GlassSheetWalk,direct:vec3<f32>,continuous:bool};
+fn glass_camera_sheet(t:Triangle,point:PrecisePoint,source_triangle:u32,incident:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,outside:f32,inside:f32,wavelength:f32,remaining:u32,stratum:u32,strata:u32,prior_continuous:bool,prefix:vec3<f32>,lights:ptr<function,array<vec4<u32>,6>>,light_count:ptr<function,u32>,selection_rng:ptr<function,u32>,rng:ptr<function,u32>)->GlassRadiantSheet {
+ var direction=incident;var weight=vec3<f32>(1.0);var internal=false;
+ var direct=vec3<f32>(0.0);var continuous=prior_continuous;
+ let outward=unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
+ for(var event=0u;event<remaining;event+=1u) {
+ let macro_normal=select(-normal,normal,dot(direction,normal)<0.0);
+ let ni=select(outside,inside,internal);let nt=select(inside,outside,internal);
+ let actual_geometric=select(-geometric,geometric,dot(direction,normal)<0.0);
+ let face_outward=select(actual_geometric,-actual_geometric,internal);
+ let side=select(-1,1,dot(face_outward,outward)>0.0);
+ if !photon_enabled() || !continuous {
+ glass_offer_light(lights,light_count,selection_rng,point,direction,prefix*weight,ni,nt,source_triangle,select(2u,3u,internal),glass_vacuum());
+ direct+=weight*photon_gather_glass(t,point.hi+point.lo,macro_normal,actual_geometric,direction,ni,nt,wavelength,side);
+ }
+ let sampled=glass_interface(t,direction,macro_normal,actual_geometric,ni,nt,wavelength,true,stratum,select(1u,strata,event==0u),rng);
+ if !sampled.valid {return GlassRadiantSheet(GlassSheetWalk(sampled.direction,vec3<f32>(0.0),event+1u,false),direct,continuous);}
+ if glass_rough_active(t,ni,nt) && !(sampled.transmitted && ni==nt) {continuous=true;}
+ direction=sampled.direction;weight*=sampled.weight;
+ if (!internal && !sampled.transmitted) || (internal && sampled.transmitted) {
+ let valid=dot(direction,normal)*dot(direction,geometric)>0.0;
+ return GlassRadiantSheet(GlassSheetWalk(direction,weight,event+1u,valid),direct,continuous);
+ }
+ internal=true;
+ let cosine=abs(dot(direction,normal));
+ if cosine==0.0 {return GlassRadiantSheet(GlassSheetWalk(direction,vec3<f32>(0.0),event+1u,false),direct,continuous);}
+ if t.parameters.w>0.0 {weight*=exp(-t.optics.xyz*(t.parameters.w/cosine));}
+ if !any(weight>vec3<f32>(0.0)) {return GlassRadiantSheet(GlassSheetWalk(direction,weight,event+1u,false),direct,continuous);}
+ }
+ return GlassRadiantSheet(GlassSheetWalk(direction,vec3<f32>(0.0),remaining,false),direct,continuous);
+}
diff --git a/crates/gpu/src/path/mod.rs b/crates/gpu/src/path/mod.rs
index fbf741222b..c6091a6c0d 100644
--- a/crates/gpu/src/path/mod.rs
+++ b/crates/gpu/src/path/mod.rs
@@ -25,13 +25,13 @@ mod adaptive;
mod denoise;
mod dispatch;
mod media_hierarchy;
+mod photons;
mod scene;
#[cfg(test)]
mod tests;
mod textures;
-// Disjoint glass admits at most one active medium. Fixed local array sizes let
-// native compilers discard the unused fifteen entries without changing nested
-// transport's sixteen-medium limit. Both programs share every shader operation.
+// Opaque producers specialize away dielectric traversal and use a single
+// unused medium slot. Optical producers share the sixteen-medium shader.
macro_rules! path_shader {
($capacity:literal) => {
concat!(
@@ -48,7 +48,13 @@ macro_rules! path_shader {
"\n",
include_str!("aging.wgsl"),
"\n",
- include_str!("punctual.wgsl")
+ include_str!("punctual.wgsl"),
+ "\n",
+ include_str!("glass.wgsl"),
+ "\n",
+ include_str!("glass_lighting.wgsl"),
+ "\n",
+ include_str!("photons_disabled.wgsl")
)
};
}
@@ -159,10 +165,11 @@ fn device_limits(supported: wgpu::Limits) -> Result<wgpu::Limits> {
// downlevel defaults unnecessarily capped large CAD geometry at 128 MiB.
let storage = supported.max_storage_buffer_binding_size.min(1024 * 1024 * 1024);
let buffer = supported.max_buffer_size.min(1024 * 1024 * 1024);
+ let optional_photon_buffers = supported.max_storage_buffers_per_shader_stage.min(7);
let mut limits = wgpu::Limits::downlevel_defaults().using_resolution(supported);
limits.max_storage_buffer_binding_size = storage.min(buffer);
limits.max_buffer_size = buffer;
- limits.max_storage_buffers_per_shader_stage = PATH_STORAGE_BUFFERS;
+ limits.max_storage_buffers_per_shader_stage = optional_photon_buffers;
Ok(limits)
}
fn open_device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue)> {
@@ -193,6 +200,11 @@ struct Context {
scene_pipelines: [std::sync::OnceLock<wgpu::ComputePipeline>; SCENE_PIPELINE_CACHE_SLOTS],
// Built and warmed by the first denoised job, then shared by later ones.
denoise: std::sync::OnceLock<denoise::Pipelines>,
+ // Only authored caustics compile/retain the seven-storage-buffer variant.
+ photons: std::sync::OnceLock<photons::Pipelines>,
+ // Optical hard-light connections are specialized away in the legacy program.
+ glass: std::sync::OnceLock<GlassPipelines>,
+ photon_glass: std::sync::OnceLock<GlassPipelines>,
layout: wgpu::BindGroupLayout,
}
impl Context {
@@ -209,6 +221,7 @@ impl Context {
fn wait(&self, submission: wgpu::SubmissionIndex, timeout: Duration) -> Result<()> {
wait_device(&self.device, &self.healthy, submission, timeout)
}
+ #[cfg(test)]
fn prepared_scene_pipeline(&self, opaque: bool, maps: bool, nested: bool) -> Result<&wgpu::ComputePipeline> {
let Some(index) = scene_pipeline_variant(opaque, maps, nested) else { return Ok(&self.pipeline) };
self.scene_pipelines.get(index).and_then(std::sync::OnceLock::get).ok_or_else(|| gpu("captured scene has no prepared pipeline"))
@@ -227,7 +240,7 @@ impl Context {
let scopes = scopes(&self.device);
let shader = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("gpu-path captured scene"),
- source: wgpu::ShaderSource::Wgsl(if opaque || nested { SHADER } else { SINGLE_MEDIUM_SHADER }.into()),
+ source: wgpu::ShaderSource::Wgsl(scene_shader(opaque).into()),
});
let layout = self.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("gpu-path captured scene"),
@@ -285,8 +298,10 @@ impl Executor {
});
let compiling = one_compile_at_a_time();
let scopes = scopes(&device);
- let shader =
- device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("gpu-path"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("gpu-path"),
+ source: wgpu::ShaderSource::Wgsl(scene_shader(true).into()),
+ });
let entries: Vec<_> = (0..7)
.map(|binding| wgpu::BindGroupLayoutEntry {
binding,
@@ -327,6 +342,9 @@ impl Executor {
pipeline,
layout,
denoise: std::sync::OnceLock::new(),
+ photons: std::sync::OnceLock::new(),
+ glass: std::sync::OnceLock::new(),
+ photon_glass: std::sync::OnceLock::new(),
scene_pipelines: std::array::from_fn(|_| std::sync::OnceLock::new()),
});
// The original host prepared glass before advertising readiness. Keep the
@@ -336,6 +354,71 @@ impl Executor {
}
}
+fn needs_glass_lighting(scene: &ProductScene) -> bool {
+ let active = |transmission: Option<solidcraft_render::transmission::Transmission>| {
+ transmission.is_some_and(|material| {
+ material.model().is_some_and(|model| model.roughness > 0.0) || material.subsurface().is_some_and(|medium| medium.active())
+ })
+ };
+ scene.meshes.iter().any(|body| active(body.transmission) || body.faces.iter().any(|face| active(face.transmission)))
+}
+
+#[derive(Clone)]
+struct GlassPipelines {
+ camera: wgpu::ComputePipeline,
+ resolve: wgpu::ComputePipeline,
+}
+
+// One request and camera value per path in the largest admitted tile, reusing
+// the accumulation binding. No extra image plane or storage binding is needed.
+fn glass_tile_bytes(scene: &ProductScene, request: &ImageRequest) -> u64 {
+ if needs_glass_lighting(scene) { (u64::from(request.width) * u64::from(request.height)).min(u64::from(dispatch::MAX_PATHS)) * 128 } else { 0 }
+}
+
+fn glass_pipeline(context: &Context, layout: &wgpu::BindGroupLayout, caustics: bool, cancel: &CancelToken) -> Result<GlassPipelines> {
+ cancel.check()?;
+ let slot = if caustics { &context.photon_glass } else { &context.glass };
+ if let Some(pipeline) = slot.get() {
+ return Ok(pipeline.clone());
+ }
+ let source = if caustics { std::borrow::Cow::Owned(photons::shader_source()?) } else { std::borrow::Cow::Borrowed(SHADER) };
+ let compiling = one_compile_at_a_time();
+ cancel.check()?;
+ let device = &context.device;
+ let scopes = scopes(device);
+ let module = device
+ .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("gpu-path optical hard lights"), source: wgpu::ShaderSource::Wgsl(source) });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("gpu-path optical hard lights"),
+ bind_group_layouts: &[Some(layout)],
+ immediate_size: 0,
+ });
+ let constants = [("GLASS_DELTA_LIGHTS", 1.0), ("OPAQUE_SCENE", 0.0), ("HAS_TEXTURES", 1.0)];
+ let pipeline = |entry| {
+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("gpu-path optical hard lights"),
+ layout: Some(&pipeline_layout),
+ module: &module,
+ entry_point: Some(entry),
+ compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },
+ cache: None,
+ })
+ };
+ let camera = pipeline("main");
+ checked(scopes)?;
+ cancel.check()?;
+ let resolve = checked_creation(device, || Ok(pipeline("optical_resolve")))?;
+ let pipelines = GlassPipelines { camera, resolve };
+ cancel.check()?;
+ drop(compiling);
+ let placeholder = placeholder_bind(device, layout, if caustics { 8 } else { 7 })?;
+ warm_up(device, &context.queue, &pipelines.camera, &placeholder, &context.healthy)?;
+ cancel.check()?;
+ warm_up(device, &context.queue, &pipelines.resolve, &placeholder, &context.healthy)?;
+ cancel.check()?;
+ Ok(slot.get_or_init(|| pipelines).clone())
+}
+
/// Native drivers compile the path pipeline for minutes and gigabytes on a cold shader cache.
/// Executors opened side by side (parallel tests, each on its own device) compiled it together
/// until memory ran out (#6706). One compile at a time per process: the first fills the driver's
@@ -403,6 +486,13 @@ fn descriptor() -> Result<ExecutorDescriptor> {
})
}
+// RADV failed to cover mapped thin-glass pixels with the combined one-medium
+// producer. Keep the qualified full stack for optical transport. The nested
+// media option still controls admission and the actual boundary transitions.
+fn scene_shader(opaque: bool) -> &'static str {
+ if opaque { SINGLE_MEDIUM_SHADER } else { SHADER }
+}
+
fn scene_pipeline_variant(opaque: bool, maps: bool, nested: bool) -> Option<usize> {
if opaque { maps.then_some(0) } else { Some(1 + 2 * usize::from(maps) + usize::from(nested)) }
}
@@ -418,6 +508,7 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions)
return Err(JobError::new(ErrorCode::InvalidRequest, "GPU path rendering does not accept CPU raytrace options"));
}
options.validate()?;
+ photons::validate_scene(scene, options)?;
if request.studio_weights.is_some_and(|weights| weights.iter().any(|value| !value.is_finite() || !(0.0..=1.0).contains(value))) {
return Err(JobError::new(ErrorCode::InvalidRequest, "invalid studio visibility weights"));
}
@@ -488,8 +579,11 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions)
// serialized + device geometry + accumulation/readback/RGBA/PNG. These phases don't overlap.
let pixels = u64::from(request.width) * u64::from(request.height);
let denoise_bytes = pixels * if options.denoise { denoise::BYTES_PER_PIXEL + if options.adaptive.is_some() { 16 } else { 0 } } else { 0 };
+ let optical_tile_bytes = glass_tile_bytes(scene, request);
admission.pixel_scratch_bytes = pixels * 64 + denoise_bytes;
let vertex_bytes = scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::<u64>();
+ let model_bytes = admission.triangles * scene::model_bytes_per_triangle(scene);
+ admission.geometry_bytes += model_bytes;
let triangle_preparation =
(admission.triangles * 400_u64.max(scene::planar_preparation_bytes_per_triangle() as u64)).max(scene::medium_preparation_bytes(scene));
admission.preparation_bytes = (triangle_preparation + vertex_bytes * 2 + admission.face_appearances * 8)
@@ -499,6 +593,9 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions)
+ 2 * DIRECTIONAL_PARAMETER_BYTES
+ 2 * PUNCTUAL_PARAMETER_BYTES
+ 2 * PUNCTUAL_COUNTER_BYTES;
+ // Optional material lane is retained in serialized/device geometry while
+ // preparation also owns its serialization scratch. Legacy scenes add zero.
+ admission.preparation_bytes += model_bytes * 2;
admission.preparation_bytes += request.environment.as_ref().map_or(0, |source| source.admitted_bytes());
if let Some(textures) = &request.textures {
textures.validate_scene(scene)?;
@@ -525,8 +622,12 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions)
// Two pilot/budget planes plus a second readback plane. Adaptive denoising's
// independent normalized preview input is included in denoise_bytes above.
let adaptive_bytes = pixels * if options.adaptive.is_some() { 48 } else { 0 };
- admission.pixel_scratch_bytes += adaptive_bytes;
- admission.preparation_bytes += adaptive_bytes;
+ admission.pixel_scratch_bytes += adaptive_bytes + optical_tile_bytes;
+ admission.preparation_bytes += adaptive_bytes + optical_tile_bytes;
+ admission.preparation_bytes = admission
+ .preparation_bytes
+ .checked_add(photons::admission_bytes(options.caustics)?)
+ .ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "caustic photon admission overflow"))?;
admission.estimated_total_bytes = admission.geometry_bytes + admission.preparation_bytes;
if admission.estimated_total_bytes > GPU_PATH_LIMITS.max_scratch_bytes {
return Err(JobError::new(ErrorCode::LimitExceeded, "gpu-path job exceeds its bounded 8 GiB admission estimate"));
@@ -535,6 +636,12 @@ fn admission(scene: &ProductScene, request: &ImageRequest, options: JobOptions)
}
impl ImageExecutor for Executor {
+ fn supports_glass_models(&self) -> bool {
+ true
+ }
+ fn supports_caustics(&self) -> bool {
+ true
+ }
fn preview_samples(&self, options: JobOptions) -> Option<u32> {
options.preview_target().ok()
}
@@ -582,6 +689,18 @@ impl ImageExecutor for Executor {
self.context.ensure_available()?;
let a = admission(scene, request, options)?;
let device_limits = self.context.device.limits();
+ if let Some(caustics) = options.caustics {
+ if device_limits.max_storage_buffers_per_shader_stage < 7 {
+ return Err(JobError::new(
+ ErrorCode::HostUnavailable,
+ "caustics require seven GPU storage buffers; ordinary GPU images remain available",
+ ));
+ }
+ let photon_bytes = photons::buffer_bytes(caustics)?;
+ if photon_bytes > device_limits.max_storage_buffer_binding_size || photon_bytes > device_limits.max_buffer_size {
+ return Err(JobError::new(ErrorCode::LimitExceeded, "caustic photon storage exceeds the selected GPU buffer limit"));
+ }
+ }
if PARAMETER_BYTES as u64 > device_limits.max_uniform_buffer_binding_size
|| PARAMETER_BYTES as u64 > device_limits.max_buffer_size
|| FAILURE_BYTES > device_limits.max_storage_buffer_binding_size
@@ -589,16 +708,20 @@ impl ImageExecutor for Executor {
return Err(JobError::new(ErrorCode::LimitExceeded, "GPU light parameters or diagnostic storage exceed device buffer limits"));
}
let limit = device_limits.max_storage_buffer_binding_size;
- let geometry_bytes = 16 + a.triangles.max(1) * 100 + scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::<u64>();
+ let geometry_bytes = 16
+ + a.triangles.max(1) * (100 + scene::model_bytes_per_triangle(scene))
+ + scene.meshes.iter().map(|m| m.mesh.positions.len() as u64 * 32).sum::<u64>();
let texture_bytes = request.textures.as_ref().map_or(16, |t| textures::packed_bytes(t, scene.meshes.len()));
let environment_bytes =
request.environment.as_ref().map_or(48, |source| 16 + u64::from(source.info().width) * u64::from(source.info().height) * 32);
let node_bytes = a.triangles.max(1) * 64;
+ let accumulation_bytes = u64::from(request.width) * u64::from(request.height) * if options.adaptive.is_some() { 48 } else { 16 }
+ + glass_tile_bytes(scene, request);
if node_bytes > limit
|| texture_bytes > limit
|| environment_bytes > limit
|| geometry_bytes > limit
- || u64::from(request.width) * u64::from(request.height) * if options.adaptive.is_some() { 48 } else { 16 } > limit
+ || accumulation_bytes > limit
|| (options.denoise && u64::from(request.width) * u64::from(request.height) * 48 > limit)
{
return Err(JobError::new(ErrorCode::LimitExceeded, "gpu-path storage buffer exceeds this device's limit"));
@@ -678,7 +801,9 @@ struct Task {
context: Arc<Context>,
request: ImageRequest,
options: JobOptions,
+ #[cfg(test)]
opaque_scene: bool,
+ #[cfg(test)]
has_textures: bool,
cancel: CancelToken,
uniform: wgpu::Buffer,
@@ -686,6 +811,9 @@ struct Task {
failures: wgpu::Buffer,
readback: wgpu::Buffer,
bind: wgpu::BindGroup,
+ render_pipeline: wgpu::ComputePipeline,
+ optical_resolve: Option<wgpu::ComputePipeline>,
+ photons: Option<photons::Resources>,
denoiser: Option<denoise::Resources>,
sample: u32,
lane: u32,
@@ -718,11 +846,9 @@ impl Task {
validate_punctual_origin(options, request.camera.target)?;
let opaque_scene = use_opaque_pipeline(&scene, options);
let has_textures = request.textures.is_some();
- context.prepare_scene_pipeline(opaque_scene, has_textures, options.nested_media)?;
- cancel.check()?;
let start = Instant::now();
let aging = options.aging.gpu_layers([request.camera.target.x, request.camera.target.y, request.camera.target.z])?;
- let volume = if let Some(v) = options.volume.filter(|v| v.active()) {
+ let mut volume = if let Some(v) = options.volume.filter(|v| v.active()) {
let bounds = v.relative_bounds([request.camera.target.x, request.camera.target.y, request.camera.target.z])?;
[
[bounds[0][0], bounds[0][1], bounds[0][2], v.extinction_per_mm as f32],
@@ -738,7 +864,33 @@ impl Task {
let texture_upload = textures::flatten(request.textures.as_deref(), scene.meshes.len(), request.camera.target, &cancel)?;
request.textures = None; // GPU upload owns decoded pixels; release captured source bytes.
let upload = scene::flatten_with_media(&scene, request.camera.target, &cancel, options.nested_media)?;
+ // This uniform lane was spare. Keep the material offset mask that the
+ // mapped opaque shader has qualified on RADV.
+ volume[2][3] = if upload.active_glass_model { 1.0 } else { 0.0 };
+ photons::validate_punctual_origins(&scene, request.camera.target, options, upload.epsilon, &cancel)?;
let bvh_ms = start.elapsed().as_secs_f64() * 1000.0;
+ let source_count = options.lighting.map_or_else(
+ || if request.environment.is_none() { 3 } else { 0 },
+ |lighting| lighting.directional_lights.iter().count() as u32 + lighting.punctual_lights.iter().count() as u32,
+ );
+ let photons = options.caustics.map(|options| photons::Resources::new(&context, options, &upload.nodes, source_count)).transpose()?;
+ cancel.check()?;
+ let glass_lighting = needs_glass_lighting(&scene);
+ let optical_tile_bytes = glass_tile_bytes(&scene, &request);
+ let optical_pipelines = if glass_lighting {
+ Some(glass_pipeline(&context, photons.as_ref().map_or(&context.layout, |resources| &resources.layout), photons.is_some(), &cancel)?)
+ } else {
+ None
+ };
+ let render_pipeline = if let Some(pipelines) = &optical_pipelines {
+ pipelines.camera.clone()
+ } else if let Some(resources) = &photons {
+ resources.render.clone()
+ } else {
+ context.prepare_scene_pipeline(opaque_scene, has_textures, options.nested_media)?.clone()
+ };
+ let optical_resolve = optical_pipelines.map(|pipelines| pipelines.resolve);
+ cancel.check()?;
let mut upload_bytes = (upload.geometry.len() + upload.nodes.len() + texture_upload.len()) as u64;
let environment_bytes = prepare_environment(&request, &cancel)?;
cancel.check()?;
@@ -759,7 +911,7 @@ impl Task {
let size = u64::from(request.width) * u64::from(request.height) * 16;
let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("path accumulation"),
- size: size * if options.adaptive.is_some() { 3 } else { 1 },
+ size: size * if options.adaptive.is_some() { 3 } else { 1 } + optical_tile_bytes,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
@@ -782,7 +934,14 @@ impl Task {
.collect();
entries.push(wgpu::BindGroupEntry { binding: 5, resource: texture_buffer.as_entire_binding() });
entries.push(wgpu::BindGroupEntry { binding: 6, resource: failures.as_entire_binding() });
- let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("gpu-path"), layout: &context.layout, entries: &entries });
+ if let Some(resources) = &photons {
+ entries.push(wgpu::BindGroupEntry { binding: 7, resource: resources.buffer.as_entire_binding() });
+ }
+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("gpu-path"),
+ layout: photons.as_ref().map_or(&context.layout, |resources| &resources.layout),
+ entries: &entries,
+ });
let denoiser = if options.denoise {
Some(denoise::Resources::new(
&context,
@@ -802,9 +961,28 @@ impl Task {
let upload_ms = uploading.elapsed().as_secs_f64() * 1000.0;
log::info!("gpu-path BVH {bvh_ms:.3} ms, upload {upload_bytes} bytes in {upload_ms:.3} ms");
cancel.check()?;
+ if let Some(resources) = &photons {
+ resources.warm_up_actual(&context, &uniform, &bind, &cancel)?;
+ }
+ if glass_lighting {
+ cancel.check()?;
+ context.ensure_available()?;
+ checked_creation(&context.device, || {
+ context.queue.write_buffer(&uniform, 0, &[0; PARAMETER_BYTES]);
+ Ok(())
+ })?;
+ warm_up(&context.device, &context.queue, &render_pipeline, &bind, &context.healthy)?;
+ cancel.check()?;
+ if let Some(resolve) = &optical_resolve {
+ warm_up(&context.device, &context.queue, resolve, &bind, &context.healthy)?;
+ };
+ cancel.check()?;
+ }
Ok(Self {
dispatch_budget: Default::default(),
+ #[cfg(test)]
opaque_scene,
+ #[cfg(test)]
has_textures,
context,
request,
@@ -815,6 +993,9 @@ impl Task {
failures,
readback,
bind,
+ render_pipeline,
+ optical_resolve,
+ photons,
denoiser,
sample: 0,
lane: 0,
@@ -965,6 +1146,13 @@ impl Task {
fn dispatch(&mut self) -> Result<()> {
self.cancel.check()?;
self.context.ensure_available()?;
+ if let Some(resources) = self.photons.as_ref().filter(|resources| !resources.ready()) {
+ let parameters = self.parameters(resources.count())?;
+ if let Some(resources) = &mut self.photons {
+ resources.step(&self.context, &self.uniform, &self.bind, &parameters, &self.cancel)?;
+ }
+ return Ok(());
+ }
let dispatch_started = Instant::now();
let pixels = self.request.width * self.request.height;
let count = self.dispatch_budget.count(pixels - self.offset);
@@ -974,8 +1162,13 @@ impl Task {
let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("path tile") });
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("path tile"), timestamp_writes: None });
- let pipeline = context.prepared_scene_pipeline(self.opaque_scene, self.has_textures, self.options.nested_media)?;
- pass.set_pipeline(pipeline);
+ pass.set_pipeline(&self.render_pipeline);
+ pass.set_bind_group(0, &self.bind, &[]);
+ pass.dispatch_workgroups(count.div_ceil(PATH_WORKGROUP_SIZE), 1, 1);
+ }
+ if let Some(resolve) = &self.optical_resolve {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("path optical resolve"), timestamp_writes: None });
+ pass.set_pipeline(resolve);
pass.set_bind_group(0, &self.bind, &[]);
pass.dispatch_workgroups(count.div_ceil(PATH_WORKGROUP_SIZE), 1, 1);
}
@@ -1002,6 +1195,7 @@ impl Task {
let maximum = (self.request.width * self.request.height)
.div_ceil(dispatch::MIN_PATHS)
.checked_mul(self.options.transmission_samples)
+ .and_then(|count| count.checked_add(self.photons.as_ref().map_or(0, photons::Resources::maximum_quanta)))
.ok_or_else(|| gpu("test sample wave count overflow"))?;
for _ in 0..maximum {
self.dispatch()?;
@@ -1052,6 +1246,18 @@ impl Task {
None
};
let word = |i: usize| failures.as_chunks::<4>().0.get(i).map_or(0, |w| u32::from_le_bytes(*w));
+ if word(7) & 16 != 0 {
+ return Err(JobError::new(ErrorCode::InvalidScene, "rough optical response exceeds GPU arithmetic precision"));
+ }
+ if word(7) & 8 != 0 {
+ return Err(JobError::new(ErrorCode::InvalidScene, "optical light-event count exceeds the admitted camera depth"));
+ }
+ if word(7) & 4 != 0 {
+ return Err(JobError::new(ErrorCode::InvalidScene, "caustic photon medium origin or transition is ambiguous"));
+ }
+ if word(7) & 2 != 0 {
+ return Err(JobError::new(ErrorCode::InvalidScene, "positive-thickness index-matched sheet has no finite grazing optical path"));
+ }
if word(7) != 0 {
return Err(JobError::new(ErrorCode::Internal, "nonfinite or negative pilot/production path radiance"));
}
@@ -1173,6 +1379,9 @@ impl ImageWork for Task {
if self.sample < self.target_samples() {
let before = self.sample;
self.dispatch()?;
+ if let Some(resources) = self.photons.as_ref().filter(|resources| !resources.ready()) {
+ return Ok(TaskPoll::Pending(resources.progress()));
+ }
if self.preview_enabled && self.sample > before && self.sample < self.target_samples() {
// sample advances only after every tile and Fresnel stratum of
// the pass. Readback cannot observe a partially updated film.
diff --git a/crates/gpu/src/path/optical_media_tests.rs b/crates/gpu/src/path/optical_media_tests.rs
index b4b8167240..3192e7b3dc 100644
--- a/crates/gpu/src/path/optical_media_tests.rs
+++ b/crates/gpu/src/path/optical_media_tests.rs
@@ -247,6 +247,14 @@ fn gpu_origin_query_uses_only_closed_boundaries_and_refuses_surface_and_silhouet
let source = [
SHADER,
r#"
+// Independent oracle for the production query's reuse of its root entry.
+fn origin_vacuum(o:vec3<f32>,d:vec3<f32>)->bool {
+ let root=nodes[0];
+ if root.first==0xffffffffu {return true;}
+ if all(o>=root.lo) && all(o<=root.hi) {return false;}
+ let entry=box_entry_padded(root,o,d,FAR,u.lighting.x);
+ return entry<0.0 || entry>u.lighting.x;
+}
@compute @workgroup_size(1) fn origin_reference() {
let boundary=origin_boundary(u.eye.xyz,u.right.xyz);
var media:array<Medium,16>;var count=0u;var valid=boundary.valid;
@@ -255,7 +263,7 @@ fn gpu_origin_query_uses_only_closed_boundaries_and_refuses_surface_and_silhouet
if valid && count>0u { sigma=media[count-1u].sigma;scatter=media[count-1u].scatter;outer=media[0].ior;top=media[count-1u].ior; }
accumulation[0]=vec4<f32>(sigma,select(0.0,1.0,valid));
accumulation[1]=vec4<f32>(outer,top,f32(count),select(0.0,1.0,boundary.hit.triangle!=0xffffffffu));
- accumulation[2]=vec4<f32>(scatter,0.0,1.0);
+ accumulation[2]=vec4<f32>(scatter,select(0.0,1.0,origin_vacuum(u.eye.xyz,u.right.xyz)),1.0);
}
"#,
]
@@ -370,11 +378,11 @@ fn gpu_origin_query_uses_only_closed_boundaries_and_refuses_surface_and_silhouet
(Vec3::new(0.25, 0.125, 1.0), -Vec3::Z, None),
(Vec3::new(0.25, 0.125, 1.0), Vec3::Z, None),
(Vec3::new(5.0, 5.0, 1.0), -Vec3::Z, None),
- (Vec3::new(10.0, 0.0, 3.5), -Vec3::Z, None),
- (Vec3::new(10.0, 10.0, 3.5), -Vec3::Z, None),
+ (Vec3::new(10.0, 0.0, 3.5), -Vec3::Z, Some((0, Vec3::ZERO, 0.0, 0.0))),
+ (Vec3::new(10.0, 10.0, 3.5), -Vec3::Z, Some((0, Vec3::ZERO, 0.0, 0.0))),
(Vec3::new(0.25, 0.125, 1.0 + epsilon * 0.5), -Vec3::Z, None),
(Vec3::new(0.25, 0.125, 1.0 - epsilon * 0.5), Vec3::Z, None),
- (Vec3::new(0.25, 0.125, 1_000_000_000.0), -Vec3::Z, None),
+ (Vec3::new(0.25, 0.125, 1_000_000_000.0), -Vec3::Z, Some((0, Vec3::ZERO, 0.0, 0.0))),
(Vec3::new(-8.0, 5.0, 0.25), Vec3::X, None),
(Vec3::new(-8.0, 2.0, 0.0), Vec3::new(1.0, 1.0, 0.0) / 2.0_f64.sqrt(), None),
];
@@ -416,6 +424,49 @@ fn gpu_origin_query_uses_only_closed_boundaries_and_refuses_surface_and_silhouet
}
}
}
+ // A future edge/vertex cannot make a provably outside origin ambiguous.
+ // The complete origin-to-primary-minimum interval must nevertheless remain
+ // clear: a just-outside entry cannot be skipped before an inside opaque hit.
+ let mut task =
+ Task::new(context.clone(), nested(), request(2), JobOptions { nested_media: true, samples: 1, ..Default::default() }, CancelToken::default())
+ .unwrap();
+ let epsilon = f64::from(task.epsilon);
+ for (origin, direction, vacuum, valid, count) in [
+ (Vec3::new(10.0, 0.0, 4.0), -Vec3::Z, true, true, 0.0),
+ (Vec3::new(10.0, 10.0, 4.0), -Vec3::Z, true, true, 0.0),
+ (Vec3::new(0.25, 0.125, 2.0 + epsilon * 4.0), -Vec3::Z, true, true, 0.0),
+ (Vec3::new(0.25, 0.125, 2.0 + epsilon * 0.5), -Vec3::Z, false, false, 0.0),
+ (Vec3::new(0.25, 0.125, 2.0 - epsilon * 0.5), Vec3::Z, false, false, 0.0),
+ (Vec3::new(0.25, 0.125, 2.0), -Vec3::Z, false, false, 0.0),
+ (Vec3::new(0.25, 0.125, 2.0), Vec3::Z, false, false, 0.0),
+ (Vec3::new(10.0, 0.0, 2.0), -Vec3::Z, false, false, 0.0),
+ (Vec3::new(0.25, 0.125, 0.0), -Vec3::Z, false, true, 2.0),
+ ] {
+ let mut params = task.parameters(1).unwrap();
+ let mut values = Vec::new();
+ scene::vector(&mut values, origin, 0.0);
+ scene::vector(&mut values, direction, 0.0);
+ params[32..64].copy_from_slice(&values);
+ context.queue.write_buffer(&task.uniform, 0, &params);
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ let value = task.read_linear().unwrap();
+ assert_eq!(value[2][2] != 0.0, vacuum, "vacuum certificate origin={origin:?} direction={direction:?}: {value:?}");
+ assert_eq!(value[0][3] != 0.0, valid, "launch-interval certificate origin={origin:?} direction={direction:?}: {value:?}");
+ if valid {
+ assert_eq!(value[1][2], count);
+ }
+ if vacuum {
+ assert_eq!(value[1][3], 0.0, "vacuum proof must bypass future ambiguous crossings");
+ }
+ }
}
fn origin_emitter_fixture() -> ProductScene {
diff --git a/crates/gpu/src/path/path.wgsl b/crates/gpu/src/path/path.wgsl
index 6439dc8fd8..3e26e69430 100644
--- a/crates/gpu/src/path/path.wgsl
+++ b/crates/gpu/src/path/path.wgsl
@@ -8,6 +8,7 @@ struct Triangle {
base: vec4<f32>, parameters: vec4<f32>, optics: vec4<f32>,
coat: vec4<f32>, // weight, perceptual roughness, IOR, shadow transmission flag
interior: vec4<f32>, // scattering/mm, HG g, flags (stage=1, scalar face=2), immediate parent triangle+1
+ glass: vec4<f32>, // optional roughness, Abbe number, film thickness/nm, film IOR
};
struct Node { lo: vec3<f32>, first: u32, hi: vec3<f32>, count: u32 };
struct AreaLight { center: vec4<f32>, u: vec4<f32>, v: vec4<f32>, radiance: vec4<f32> };
@@ -31,7 +32,7 @@ struct Params {
adaptive_error: vec4<f32>, // relative RGB, absolute RGB, absolute coverage, current production stratum
volume_min: vec4<f32>, // camera-relative bounds minimum, extinction/mm
volume_max: vec4<f32>, // camera-relative bounds maximum, HG mean cosine
- volume_albedo: vec4<f32>, // RGB single-scattering albedo, reserved
+ volume_albedo: vec4<f32>, // RGB single-scattering albedo, active glass model flag
aging: array<AgingLayer,8>,
directional_lights: array<DirectionalLight,8>,
punctual_lights: array<PunctualLight,8>,
@@ -74,8 +75,11 @@ fn triangle(index: u32) -> Triangle {
let a = geometry[1]+geometry[word]*8u;
let b = geometry[1]+geometry[word+1u]*8u;
let c = geometry[1]+geometry[word+2u]*8u;
- let material = geometry[2]+geometry[word+3u]*20u;
- return Triangle(vector_at(a),vector_at(b),vector_at(c),vector_at(a+4u),vector_at(b+4u),vector_at(c+4u),vector_at(material),vector_at(material+4u),vector_at(material+8u),vector_at(material+12u),vector_at(material+16u));
+ let has_model=(geometry[2]&0x80000000u)!=0u;
+ let material = (geometry[2]&0x3fffffffu)+geometry[word+3u]*select(20u,24u,has_model);
+ var glass=vec4<f32>(0.0);
+ if has_model {glass=vector_at(material+20u);}
+ return Triangle(vector_at(a),vector_at(b),vector_at(c),vector_at(a+4u),vector_at(b+4u),vector_at(c+4u),vector_at(material),vector_at(material+4u),vector_at(material+8u),vector_at(material+12u),vector_at(material+16u),glass);
}
// Exact s/p power reflectance and transmitted cosine; -1 denotes TIR.
@@ -97,8 +101,19 @@ fn sheet_polarization(r: f32, a: vec3<f32>) -> Sheet {
return Sheet(vec3<f32>(r)+(1.0-r)*(1.0-r)*r*a*a/denominator,(1.0-r)*(1.0-r)*a/denominator);
}
fn sheet(t: Triangle, f: vec3<f32>) -> Sheet {
- if f.z <= 0.0 { return Sheet(vec3<f32>(1.0),vec3<f32>(0.0)); }
- let attenuation = exp(-t.optics.xyz*(t.parameters.w/f.z));
+ if f.z < 0.0 { return Sheet(vec3<f32>(1.0),vec3<f32>(0.0)); }
+ // An index-matched zero-thickness sheet has no optical path or interface,
+ // including exact grazing. Avoid both 0/0 and an invented opaque boundary.
+ var attenuation = vec3<f32>(1.0);
+ if t.parameters.w > 0.0 {
+ if f.z == 0.0 {
+ // No finite path exists for a positive-thickness tangent sheet.
+ // Share the retained diagnostic word without changing buffer layout.
+ atomicOr(&failures[7],2u);
+ return Sheet(vec3<f32>(0.0),vec3<f32>(0.0));
+ }
+ attenuation = exp(-t.optics.xyz*(t.parameters.w/f.z));
+ }
let s = sheet_polarization(f.x,attenuation);
let p = sheet_polarization(f.y,attenuation);
return Sheet((s.reflection+p.reflection)*0.5,(s.transmission+p.transmission)*0.5);
@@ -108,6 +123,9 @@ struct Medium { id: f32, ior: f32, sigma: vec3<f32>, scatter: vec2<f32> };
// inside a liquid or a ray starts on an opaque object inside a container. Parent
// references are immutable CPU-certified material references, never AABB guesses.
fn initialize_media(hit_index:u32,d:vec3<f32>,stack:ptr<function,array<Medium,MEDIUM_CAPACITY>>,count:ptr<function,u32>) -> bool {
+ return initialize_media_spectral(hit_index,d,stack,count,0.0);
+}
+fn initialize_media_spectral(hit_index:u32,d:vec3<f32>,stack:ptr<function,array<Medium,MEDIUM_CAPACITY>>,count:ptr<function,u32>,wavelength:f32) -> bool {
let first=triangle(hit_index);
if first.base.w<=0.0 || first.parameters.w>=0.0 {return true;}
let outward=unit(cross(first.p1.xyz-first.p0.xyz,first.p2.xyz-first.p0.xyz));
@@ -117,7 +135,7 @@ fn initialize_media(hit_index:u32,d:vec3<f32>,stack:ptr<function,array<Medium,ME
while reference>0u {
if length>=MEDIUM_CAPACITY {return false;}
let t=triangle(reference-1u);
- (*stack)[length]=Medium(t.optics.w,t.parameters.z,t.optics.xyz,t.interior.xy);
+ (*stack)[length]=Medium(t.optics.w,glass_ior(t.parameters.z,t.glass.y,wavelength),t.optics.xyz,t.interior.xy);
reference=u32(t.interior.w);
length+=1u;
}
@@ -722,6 +740,10 @@ fn origin_boundary(o: vec3<f32>, d: vec3<f32>) -> OriginBoundary {
if nodes[0].first==0xffffffffu { return OriginBoundary(hit,true); }
entry[0]=box_entry_padded(nodes[0],o,d,FAR,u.lighting.x);
if entry[0]<0.0 { return OriginBoundary(hit,true); }
+ // Reuse this already-computed bound: an outside origin is vacuum, and
+ // entering even the padded root after the primary minimum proves its
+ // launch interval clear. Near-boundary origins still take the full query.
+ if entry[0]>u.lighting.x && (any(o<nodes[0].lo) || any(o>nodes[0].hi)) {return OriginBoundary(hit,true);}
stack[0]=0u;var size=1u;
loop {
if size==0u { break; }
@@ -961,6 +983,7 @@ const FIXED_LIGHTS = array<vec4<f32>,3>(vec4<f32>(0.6,0.0,0.8,3.0),vec4<f32>(-0.
// directions follow without consuming random numbers. Without explicit lighting
// the three fixed lights are used.
fn direct_light(t: Triangle, position: vec3<f32>, physical: PrecisePoint, o: vec3<f32>, n: vec3<f32>, geometric: vec3<f32>, v: vec3<f32>, remaining: u32, rng: ptr<function,u32>) -> vec3<f32> {
+ transport_connection_origin=physical.hi;transport_connection_origin_low=physical.lo;
var result = vec3<f32>(0.0);
let opaque = 1.0-t.base.w;
let studio = u.environment.w > 0.0;
@@ -973,6 +996,7 @@ fn direct_light(t: Triangle, position: vec3<f32>, physical: PrecisePoint, o: vec
var shadow_distance = FAR;
var shadow_origin = o;
var shadow_origin_low = vec3<f32>(0.0);
+ if transport_medium_id!=0.0 {shadow_origin=physical.hi;shadow_origin_low=physical.lo;}
var punctual = false;
var physical_distance = FAR;
if !studio {
@@ -986,7 +1010,7 @@ fn direct_light(t: Triangle, position: vec3<f32>, physical: PrecisePoint, o: vec
let point = light.center.xyz + light.u.xyz*(2.0*random(rng)-1.0) + light.v.xyz*(2.0*random(rng)-1.0);
let delta = point-position;
sample = EnvironmentSample(unit(delta),light.radiance.xyz,area_pdf(light,delta));
- let shadow = point-o;
+ let shadow = precise_point_delta(point,vec3<f32>(0.0),shadow_origin,shadow_origin_low);
shadow_direction = unit(shadow);
shadow_distance = length(shadow);
} else if source==area_count {
@@ -1016,7 +1040,7 @@ fn direct_light(t: Triangle, position: vec3<f32>, physical: PrecisePoint, o: vec
if !punctual_radiance_valid(contribution) { punctual_count(1u); continue; }
// Irradiance uses the physical point; the robust connection is
// separately re-aimed from an offset of that same precise point.
- let shifted=punctual_offset(physical,geometric*(u.lighting.x*2.0));
+ let shifted=punctual_offset(physical,select(geometric*(u.lighting.x*2.0),vec3<f32>(0.0),transport_medium_id!=0.0));
shadow_origin=shifted.hi;
shadow_origin_low=shifted.lo;
let connection=precise_point_delta(light.position.xyz,light.position_low.xyz,shadow_origin,shadow_origin_low);
@@ -1031,7 +1055,7 @@ fn direct_light(t: Triangle, position: vec3<f32>, physical: PrecisePoint, o: vec
}
// Studio emitters block a connection that passes them; studio volumes attenuate it.
var visibility = blocked_shadow();
- let shadow_minimum=select(u.lighting.x,0.0,punctual);
+ let shadow_minimum=select(u.lighting.x,0.0,punctual || transport_medium_id!=0.0);
let emitter_limit=shadow_distance-select(u.lighting.x*2.0,0.0,punctual);
if !studio || emitter_hit_precise(shadow_origin,shadow_origin_low,shadow_direction,shadow_minimum).distance>=emitter_limit {
visibility = shadow_transmittance(shadow_origin,shadow_origin_low,shadow_direction,shadow_distance,shadow_minimum);
@@ -1075,6 +1099,10 @@ fn primary_ray(uv: vec2<f32>, lens_sample: vec2<f32>) -> CameraRay {
return CameraRay(o,d);
}
fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
+ if GLASS_DELTA_LIGHTS {transport_boundary_connection=false;}
+ transport_wavelength=0.0;transport_medium_id=0.0;transport_medium_ior=1.0;
+ transport_medium_sigma=vec3<f32>(0.0);transport_medium_scatter=0.0;transport_source_triangle=0xffffffffu;
+ transport_connection_origin=vec3<f32>(0.0);transport_connection_origin_low=vec3<f32>(0.0);
var ordinal = u.image.z;
var salt = 0u;
if u.adaptive_budget.x > 0u {
@@ -1102,10 +1130,20 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
// paths from an opaque bounce. Camera and reflected paths stay physical.
var suppress_direct = false;
var throughput = vec3<f32>(1.0);
+ var wavelength=0.0;
+ if (geometry[2]&0x40000000u)!=0u {
+ let channel=min(2u,u32(random(&rng)*3.0));
+ wavelength=glass_wavelength(channel);
+ throughput=vec3<f32>(0.0);throughput[channel]=3.0;
+ }
+ transport_wavelength=wavelength;
var radiance = vec3<f32>(0.0);
var coverage = 0.0;
var previous_pdf = 0.0;
var previous_delta = true;
+ var continuous_prefix=false;
+ var optical_lights:array<vec4<u32>,6>;var optical_light_count=0u;
+ var optical_light_rng=pixel*0x68bc21ebu ^ ordinal*0x02e5be93u ^ u.sampling.x ^ salt ^ lane*0x967a889bu ^ 0x5bd1e995u;
var media: array<Medium,MEDIUM_CAPACITY>;
var medium_count = 0u;
var texture_path_length = 0.0;
@@ -1123,7 +1161,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
// initializer would only write the existing zero count again.
let vacuum=first.interior.w==0.0 && dot(unit(cross(first.p1.xyz-first.p0.xyz,first.p2.xyz-first.p0.xyz)),d)<0.0;
if !vacuum {
- if !initialize_media(boundary.hit.triangle,d,&media,&medium_count) { return medium_failure(radiance,coverage,pixel,0u,4u); }
+ if !initialize_media_spectral(boundary.hit.triangle,d,&media,&medium_count,wavelength) { return medium_failure(radiance,coverage,pixel,0u,4u); }
}
}
}
@@ -1134,7 +1172,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
// The complete origin query exclusively owns primary classification.
// Retain the established fallback for later opaque/thin surface launches.
if !OPAQUE_SCENE && u.lighting.w>0.0 && bounce>0u && medium_count==0u && hit.triangle!=0xffffffffu {
- if !initialize_media(hit.triangle,d,&media,&medium_count) {return medium_failure(radiance,coverage,pixel,bounce,4u);}
+ if !initialize_media_spectral(hit.triangle,d,&media,&medium_count,wavelength) {return medium_failure(radiance,coverage,pixel,bounce,4u);}
}
if medium_count>0u && media[medium_count-1u].scatter.x>0.0 {
let current=media[medium_count-1u];
@@ -1147,9 +1185,16 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
throughput*=exp(-current.sigma*length(traversed));
coverage=1.0;
if !any(throughput>vec3<f32>(0.0)) {break;}
- // Homogeneous random walk without a competing next-event light
- // connection through a refracting boundary. Do not invent a
- // straight-shadow approximation or apply a mismatched MIS weight.
+ if GLASS_DELTA_LIGHTS {
+ if !photon_enabled() || !continuous_prefix {
+ glass_offer_light(&optical_lights,&optical_light_count,&optical_light_rng,PrecisePoint(position,vec3<f32>(0.0)),d,throughput,current.ior,current.ior,0xffffffffu,1u,current);
+ radiance+=throughput*photon_gather_volume(position,d,current);
+ }
+ continuous_prefix=true;
+ }
+ // HG delta-source NEE above covers contained straight connections;
+ // refracting-boundary suffixes use photons when enabled. Finite
+ // source endpoints retain the random walk's complete weight.
d=sample_hg(d,current.scatter.y,&rng);
previous_delta=true;previous_pdf=0.0;suppress_direct=false;
previous_position=position;previous_position_low=vec3<f32>(0.0);
@@ -1157,6 +1202,10 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
o=position;o_low=vec3<f32>(0.0);ray_excluded=0xffffffffu;ray_minimum=0.0;
continue;
}
+ // The competing BSDF endpoint density includes the probability of
+ // traversing this physical segment without an HG event, as does NEE.
+ let segment=ray_segment_precise(o,o_low,previous_position,previous_position_low,d,boundary);
+ previous_pdf*=exp(-current.scatter.x*length(segment));
}
if u.volume_min.w>0.0 {
let emitter_distance=emitter_hit_precise(o,o_low,d,ray_minimum).distance;
@@ -1245,7 +1294,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
if medium_count > 0u {ni = media[medium_count-1u].ior;}
var position = surface_point(captured,hit.bary);
var position_low = vec3<f32>(0.0);
- if captured.base.w>0.0 && captured.parameters.w<0.0 {
+ if (captured.base.w>0.0 && (captured.parameters.w<0.0 || GLASS_DELTA_LIGHTS)) || medium_count>0u {
let point=surface_point_precise(captured,hit.bary);
position=point.hi;position_low=point.lo;
}
@@ -1257,18 +1306,23 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
}
previous_position = position; previous_position_low=position_low;
o = position + geometric*(u.lighting.x*2.0); o_low=vec3<f32>(0.0);
- // Captured dielectric flags are exactly one, and opaque flags zero.
- // Maps are admitted only on opaque bodies; aging also leaves glass
- // unchanged. Resolve glass before any sampler temporaries become live.
+ var physical=PrecisePoint(position,position_low);
+ if u.light_count.y>0.0 { physical=punctual_offset(surface_point_precise(captured,hit.bary),vec3<f32>(0.0)); }
+ transport_medium_id=0.0;transport_medium_ior=1.0;transport_medium_sigma=vec3<f32>(0.0);transport_medium_scatter=0.0;
+ transport_source_triangle=hit.triangle;
+ if medium_count>0u {
+ let current=media[medium_count-1u];transport_medium_id=current.id;transport_medium_ior=current.ior;
+ transport_medium_sigma=current.sigma;transport_medium_scatter=current.scatter.x;
+ }
+ // Glass has no opaque closure. Finish the dielectric event before
+ // making the texture sampling temporaries live.
if !OPAQUE_SCENE && captured.base.w > 0.0 && random(&rng) < captured.base.w {
let t=captured;
- let interpolated=unit(captured.n0.xyz*hit.bary.x+captured.n1.xyz*hit.bary.y+captured.n2.xyz*hit.bary.z);
+ let interpolated=unit(t.n0.xyz*hit.bary.x+t.n1.xyz*hit.bary.y+t.n2.xyz*hit.bary.z);
let winding_normal=select(interpolated,-interpolated,dot(interpolated,geometric)<0.0);
- let n=select(geometric,winding_normal,dot(winding_normal,v)>0.0);
- // The dielectric flag makes every direct-light closure weight zero;
- // direct_light consumes no random values on this zero-weight branch.
- var optical_normal=n;
- var nt = t.parameters.z;
+ var n=select(geometric,winding_normal,dot(winding_normal,v)>0.0);
+ if glass_geometric_normals() {n=geometric;}
+ var nt = glass_ior(t.parameters.z,t.glass.y,wavelength);
if t.parameters.w < 0.0 && entering && medium_count > 0u && u.lighting.w==0.0 {
return medium_failure(radiance,coverage,pixel,bounce,4u);
}
@@ -1286,24 +1340,55 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
// inside that body: the surface touches or lies within the glass,
// like a tumbler resting on a table. Start the path in its medium.
if continued || bounce == 0u { return medium_failure(radiance,coverage,pixel,bounce,2u); }
- media[0] = Medium(t.optics.w,t.parameters.z,t.optics.xyz,t.interior.xy);
+ media[0] = Medium(t.optics.w,nt,t.optics.xyz,t.interior.xy);
medium_count = 1u;
- ni = t.parameters.z;
+ ni = nt;
throughput *= exp(-t.optics.xyz*hit.distance);
}
if media[medium_count-1u].id != t.optics.w { return medium_failure(radiance,coverage,pixel,bounce,3u); }
nt = 1.0;
if medium_count > 1u { nt = media[medium_count-2u].ior; }
}
- var f = dielectric(clamp(dot(optical_normal,v),0.0,1.0),ni,nt);
- var transmitted = refract(d,optical_normal,ni/nt);
+ let rough=glass_rough_active(t,ni,nt);
+ if rough {n=glass_macro_normal(d,n,geometric,ni,nt);}
+ if t.parameters.w>=0.0 && rough {
+ var strata=1u;
+ if !stratified && u.adaptive_budget.z>1u && u.image.z>=u.adaptive_budget.x {strata=u.adaptive_budget.z;stratified=true;}
+ var walk:GlassSheetWalk;
+ if GLASS_DELTA_LIGHTS {
+ let sampled=glass_camera_sheet(t,physical,hit.triangle,d,n,geometric,ni,nt,wavelength,u.sampling.y-bounce,lane,strata,continuous_prefix,throughput,&optical_lights,&optical_light_count,&optical_light_rng,&rng);
+ radiance+=throughput*sampled.direct;continuous_prefix=sampled.continuous;walk=sampled.walk;
+ } else {walk=glass_rough_sheet(t,d,n,ni,nt,wavelength,true,u.sampling.y-bounce,lane,strata,&rng);}
+ if !walk.valid || dot(walk.direction,n)*dot(walk.direction,geometric)<=0.0 {break;}
+ throughput*=walk.weight;d=walk.direction;
+ bounce+=walk.consumed-1u;
+ previous_delta=true;previous_pdf=0.0;suppress_direct=false;
+ previous_scatter_position=position;previous_scatter_position_low=position_low;
+ // The virtual slab exits at the same physical sheet point.
+ // Keep its barycentric displacement and the launch offset.
+ o=position; o_low=position_low+d*(u.lighting.x*2.0);
+ continue;
+ }
+ if GLASS_DELTA_LIGHTS && rough && t.parameters.w<0.0 && (!photon_enabled() || !continuous_prefix) {
+ // Enabled opaque straight-shadow connections already replace this
+ // prefix's transmitted family. Reflection remains a distinct path.
+ let light_mode=select(0u,4u,t.coat.w>0.0 && (suppress_direct || !previous_delta));
+ glass_offer_light(&optical_lights,&optical_light_count,&optical_light_rng,physical,d,throughput,ni,nt,hit.triangle,light_mode,glass_vacuum());
+ radiance+=throughput*photon_gather_glass(t,shading_position,n,geometric,d,ni,nt,wavelength,0);
+ }
+ let macro_normal=n;
+ if rough {n=glass_visible_normal(n,v,t.glass.x*t.glass.x,vec2<f32>(random(&rng),random(&rng)));}
+ var f = dielectric(clamp(dot(n,v),0.0,1.0),ni,nt);
+ var transmitted = refract(d,n,ni/nt);
// A bent shading normal must not send a transmitted ray into the wrong
// geometric hemisphere. Fall back to the geometric interface there.
- if (f.z >= 0.0 && dot(transmitted,geometric) >= 0.0) || dot(reflect(d,optical_normal),geometric) <= 0.0 {
- optical_normal = geometric;
- f = dielectric(clamp(dot(optical_normal,v),0.0,1.0),ni,nt);
- transmitted = refract(d,optical_normal,ni/nt);
+ if !rough && ((f.z >= 0.0 && dot(transmitted,geometric) >= 0.0) || dot(reflect(d,n),geometric) <= 0.0) {
+ n = geometric;
+ f = dielectric(clamp(dot(n,v),0.0,1.0),ni,nt);
+ transmitted = refract(d,n,ni/nt);
}
+ let reflected_weight=glass_reflection(t,clamp(dot(n,v),0.0,1.0),ni,nt,wavelength);
+ let reflection_probability=dot(reflected_weight,vec3<f32>(1.0/3.0));
// The first Fresnel choice is stratified conditionally on the same
// primary/prefix path. Each stratum is weighted equally; later random
// dimensions use decorrelated streams, never clamped radiance.
@@ -1314,7 +1399,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
stratified = true;
}
if t.parameters.w >= 0.0 {
- let weights = sheet(t,f);
+ let weights = glass_sheet(t,f,clamp(dot(n,v),0.0,1.0),ni,nt,wavelength);
let mean_r = dot(weights.reflection,vec3<f32>(1.0/3.0));
let mean_t = dot(weights.transmission,vec3<f32>(1.0/3.0));
if mean_r+mean_t <= 0.0 { break; }
@@ -1322,7 +1407,7 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
if branch < probability {
previous_delta=true; previous_scatter_position=position; previous_scatter_position_low=position_low; suppress_direct=false;
throughput *= weights.reflection/probability;
- d = reflect(d,optical_normal);
+ d = reflect(d,n);
} else {
throughput *= weights.transmission/(1.0-probability);
if t.coat.w>0.0 { previous_pdf*=1.0-probability; }
@@ -1332,13 +1417,17 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
o = position+d*(u.lighting.x*2.0);
// Parallel thin sheet: unchanged direction, no optical displacement.
}
- } else if branch < (f.x+f.y)*0.5 {
+ } else if branch < reflection_probability {
previous_delta=true; previous_scatter_position=position; previous_scatter_position_low=position_low; suppress_direct=false;
- d = reflect(d,optical_normal);
+ if t.glass.z>0.0 {throughput*=reflected_weight/reflection_probability;}
+ d = reflect(d,n);
+ if rough && dot(d,geometric)<=0.0 {break;}
} else {
if t.coat.w>0.0 { suppress_direct=suppress_direct || !previous_delta; }
else { suppress_direct=false; }
previous_delta=true; previous_scatter_position=position; previous_scatter_position_low=position_low;
+ if rough && (f.z<0.0 || dot(transmitted,geometric)>=0.0) {break;}
+ if t.glass.z>0.0 {throughput*=(vec3<f32>(1.0)-reflected_weight)/(1.0-reflection_probability);}
if entering {
if medium_count >= MEDIUM_CAPACITY { return medium_failure(radiance,coverage,pixel,bounce,4u); }
media[medium_count] = Medium(t.optics.w,nt,t.optics.xyz,t.interior.xy);
@@ -1348,6 +1437,8 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
d = unit(transmitted);
o = position-geometric*(u.lighting.x*2.0);
}
+ if t.parameters.w<0.0 && rough {throughput*=glass_smith_weight(dot(macro_normal,v),dot(macro_normal,d),t.glass.x*t.glass.x);}
+ if GLASS_DELTA_LIGHTS && rough && !(ni==nt && dot(d,geometric)<0.0) {continuous_prefix=true;}
if dot(d,geometric) > 0.0 { o = position+geometric*(u.lighting.x*2.0); }
if t.parameters.w<0.0 {
// A finite normal offset can cross the next face near a closed
@@ -1361,6 +1452,11 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
// classified. Such directions carry negligible energy; end the path.
if abs(dot(d,geometric))<1e-6 { break; }
o=position; o_low=position_low; ray_excluded=hit.triangle; ray_minimum=0.0;
+ } else if GLASS_DELTA_LIGHTS {
+ // Even an index-matched or smooth sheet can share the active
+ // optical producer and acquire a split physical hit point.
+ let offset_direction=select(d,geometric,dot(d,geometric)>0.0);
+ o=position; o_low=position_low+offset_direction*(u.lighting.x*2.0);
}
continue;
}
@@ -1368,38 +1464,42 @@ fn sample_path_lane(pixel: u32, lane: u32) -> vec4<f32> {
let gradients=texture_gradients(map_record,geometric,d,hit.distance,texture_path_length,bounce);
let mapped_surface=texture_surface(map_record,captured.base.xyz,captured.parameters.x,captured.parameters.y,shading_position,gradients,(u32(captured.interior.z)&2u)!=0u);
// Retain immutable geometry and medium data across optical map evaluation.
- let textured=Triangle(captured.p0,captured.p1,captured.p2,captured.n0,captured.n1,captured.n2,vec4<f32>(mapped_surface.color,captured.base.w),vec4<f32>(mapped_surface.metallic,mapped_surface.roughness,captured.parameters.zw),captured.optics,captured.coat,captured.interior);
+ let textured=Triangle(captured.p0,captured.p1,captured.p2,captured.n0,captured.n1,captured.n2,vec4<f32>(mapped_surface.color,captured.base.w),vec4<f32>(mapped_surface.metallic,mapped_surface.roughness,captured.parameters.zw),captured.optics,captured.coat,captured.interior,captured.glass);
let t=aged_surface(textured,shading_position,outward);
let interpolated=unit(captured.n0.xyz*hit.bary.x+captured.n1.xyz*hit.bary.y+captured.n2.xyz*hit.bary.z);
let winding_normal=select(interpolated,-interpolated,dot(interpolated,geometric)<0.0);
let original_normal=select(geometric,winding_normal,dot(winding_normal,v)>0.0);
let mapped_normal=texture_normal(map_record,mapped_surface.normal,original_normal,geometric);
let n=select(original_normal,mapped_normal,dot(mapped_normal,v)>0.0);
- var physical=PrecisePoint(position,position_low);
- if u.light_count.y>0.0 { physical=punctual_offset(surface_point_precise(captured,hit.bary),vec3<f32>(0.0)); }
- radiance += throughput*direct_light(t,position,physical,o,n,geometric,v,u.sampling.y-bounce-1u,&rng);
+ radiance += throughput*direct_light(t,shading_position,physical,o,n,geometric,v,u.sampling.y-bounce-1u,&rng);
+ radiance += throughput*photon_gather(t,shading_position,n,geometric,v);
d = sample_surface(t,n,v,&rng);
let nl = dot(n,d);
if nl<=0.0 || dot(geometric,d)<=0.0 { break; }
let pdf = surface_pdf(t,n,v,d);
+ if GLASS_DELTA_LIGHTS {continuous_prefix=true;}
previous_pdf = (1.0-t.base.w)*pdf;
previous_scatter_position=position; previous_scatter_position_low=position_low;
previous_delta = false;
suppress_direct=false;
throughput *= brdf(t,n,v,d) * (nl/pdf);
+ if medium_count>0u {
+ o=position;o_low=position_low;ray_excluded=hit.triangle;ray_minimum=0.0;
+ }
if bounce>=3u {
let survive = clamp(max(max(throughput.x,throughput.y),throughput.z),0.05,0.95);
if random(&rng)>survive { break; }
throughput /= survive;
}
}
+ if GLASS_DELTA_LIGHTS {glass_capture_light(&optical_lights,optical_light_count,wavelength,pixel);}
return vec4<f32>(radiance,coverage);
}
fn checked_sample(pixel: u32, lane: u32) -> vec4<f32> {
let value = sample_path_lane(pixel, lane);
if !all(value >= vec4<f32>(0.0)) || !all(value <= vec4<f32>(3.4e38)) {
- atomicStore(&failures[7], 1u);
+ atomicOr(&failures[7], 1u);
}
return value;
}
@@ -1421,23 +1521,14 @@ fn adaptive_target(mean: vec4<f32>, m2: vec4<f32>) -> u32 {
return clamp(u32(max(max(need.x,need.y),max(need.z,need.w))),u.adaptive_budget.y,maximum);
}
-@compute @workgroup_size(32)
-fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
- let pixel = u.image.w + gid.x;
- let pixels = u.image.x*u.image.y;
- if gid.x >= u.sampling.z || pixel >= pixels { return; }
- let pilots = u.adaptive_budget.x;
- let strata = max(1u,u.adaptive_budget.z);
- let lane = u32(u.adaptive_error.w);
- // Settle first whether this invocation samples at all, then take the path sample at one call
- // site: every call is inlined, and three copies of the integrator were more than NVIDIA's
- // Vulkan compiler could build (#6705).
- var budget_count = 0u;
- if pilots > 0u && u.image.z >= pilots {
- budget_count = u32(accumulation[2u*pixels+pixel].x);
- if u.image.z-pilots >= budget_count { return; }
- }
- let value = sample_path(pixel);
+// Both phases finish through the same film update. Optical camera invocations
+// publish one bounded request per tile; a separate native program resolves its
+// visibility before entering this update, including final adaptive normalization.
+fn accumulate_path(pixel:u32,value:vec4<f32>) {
+ let pixels=u.image.x*u.image.y;let pilots=u.adaptive_budget.x;
+ let strata=max(1u,u.adaptive_budget.z);let lane=u32(u.adaptive_error.w);
+ var budget_count=0u;
+ if pilots>0u && u.image.z>=pilots {budget_count=u32(accumulation[2u*pixels+pixel].x);}
if pilots == 0u {
let sample = value/f32(strata);
if u.image.z == 0u && lane == 0u { accumulation[pixel] = sample; }
@@ -1464,6 +1555,37 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
// Per-pixel production means enter both raw EXR and denoising. Pilots do not.
if ordinal+1u == budget_count && lane+1u == strata { accumulation[pixel] /= f32(budget_count); }
}
+@compute @workgroup_size(32)
+fn main(@builtin(global_invocation_id) gid:vec3<u32>) {
+ let pixel=u.image.w+gid.x;let pixels=u.image.x*u.image.y;
+ if gid.x>=u.sampling.z || pixel>=pixels {return;}
+ let pilots=u.adaptive_budget.x;
+ if pilots>0u && u.image.z>=pilots && u.image.z-pilots>=u32(accumulation[2u*pixels+pixel].x) {return;}
+ if GLASS_DELTA_LIGHTS {accumulation[glass_tile_address(pixel)+6u]=vec4<f32>(0.0);}
+ let value=sample_path(pixel);
+ if GLASS_DELTA_LIGHTS {accumulation[glass_tile_address(pixel)+7u]=value;return;}
+ accumulate_path(pixel,value);
+}
+
+@compute @workgroup_size(32)
+fn optical_resolve(@builtin(global_invocation_id) gid:vec3<u32>) {
+ if !GLASS_DELTA_LIGHTS {return;}
+ let pixel=u.image.w+gid.x;let pixels=u.image.x*u.image.y;
+ if gid.x>=u.sampling.z || pixel>=pixels {return;}
+ let pilots=u.adaptive_budget.x;
+ if pilots>0u && u.image.z>=pilots && u.image.z-pilots>=u32(accumulation[2u*pixels+pixel].x) {return;}
+ let address=glass_tile_address(pixel);let header=accumulation[address+6u];
+ var packet:array<vec4<u32>,6>;
+ if header.x>0.0 {
+ for(var lane=0u;lane<6u;lane+=1u) {packet[lane]=bitcast<vec4<u32>>(accumulation[address+lane]);}
+ packet[0].w=u32(accumulation[address].w);packet[1].w=u32(accumulation[address+1u].w);
+ }
+ transport_wavelength=header.y;
+ var value=accumulation[address+7u];
+ value=vec4<f32>(value.xyz+glass_resolve_light(&packet,u32(header.x),header.y),value.w);
+ if !all(value>=vec4<f32>(0.0)) || !all(value<=vec4<f32>(3.4e38)) {atomicOr(&failures[7],1u);}
+ accumulate_path(pixel,value);
+}
// Validation entry point: exact same BRDF used by production paths, read back in tests.
@compute @workgroup_size(1)
diff --git a/crates/gpu/src/path/photons.rs b/crates/gpu/src/path/photons.rs
new file mode 100644
index 0000000000..d94ffd2108
--- /dev/null
+++ b/crates/gpu/src/path/photons.rs
@@ -0,0 +1,357 @@
+//! Opt-in, prepaid GPU caustic photon storage and cancellable measured prepasses.
+//! Legacy jobs retain the original six-storage-buffer shader/layout unchanged.
+use super::*;
+use solidcraft_render::job::CausticOptions;
+
+const HEADER_WORDS: u32 = 16;
+const RECORD_WORDS: u32 = 16;
+const DISABLED: &str = include_str!("photons_disabled.wgsl");
+const PHOTONS: &str = include_str!("photons.wgsl");
+
+pub(super) fn heads(options: CausticOptions) -> Result<u32> {
+ options.validate()?;
+ options.photons.checked_mul(2).and_then(u32::checked_next_power_of_two).ok_or_else(|| gpu("caustic hash capacity overflow"))
+}
+pub(super) fn buffer_bytes(options: CausticOptions) -> Result<u64> {
+ let words = u64::from(HEADER_WORDS) + u64::from(heads(options)?) + u64::from(options.photons) * u64::from(RECORD_WORDS);
+ words.checked_mul(4).ok_or_else(|| gpu("caustic buffer size overflow"))
+}
+pub(super) fn admission_bytes(options: Option<CausticOptions>) -> Result<u64> {
+ options.map_or(Ok(0), |options| {
+ buffer_bytes(options)?.checked_add(u64::from(HEADER_WORDS) * 4).ok_or_else(|| gpu("caustic header estimate overflow"))
+ })
+}
+
+pub(super) fn validate_scene(scene: &ProductScene, options: JobOptions) -> Result<()> {
+ let Some(caustics) = options.caustics else { return Ok(()) };
+ caustics.validate()?;
+ if options.volume.is_some_and(|volume| volume.active()) {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "caustic photons cannot combine with active external volume transport"));
+ }
+ let validate = |transmission: Option<solidcraft_render::transmission::Transmission>| -> Result<()> {
+ if let Some(optics) = transmission
+ && optics.shadow_transmission()
+ && optics.thin_wall_thickness_mm().is_none()
+ {
+ return Err(JobError::new(
+ ErrorCode::InvalidRequest,
+ "caustic photons require disabled straight closed-glass shadow transmission to avoid counting the same direct light twice",
+ ));
+ }
+ Ok(())
+ };
+ for body in &scene.meshes {
+ validate(body.transmission)?;
+ for face in &body.faces {
+ validate(face.transmission)?;
+ }
+ }
+ Ok(())
+}
+
+/// Photon origin classification currently consumes a rounded f32 point. A
+/// punctual source's retained low part must not be able to cross a nearby closed
+/// optical boundary and change that classification. Check once per source/body,
+/// without an uncharged all-triangle scan in every emitted photon invocation.
+pub(super) fn validate_punctual_origins(scene: &ProductScene, origin: Vec3, options: JobOptions, epsilon: f32, cancel: &CancelToken) -> Result<()> {
+ if options.caustics.is_none() {
+ return Ok(());
+ }
+ let closed =
+ |optics: Option<solidcraft_render::transmission::Transmission>| optics.is_some_and(|optics| optics.thin_wall_thickness_mm().is_none());
+ if let Some(lighting) = options.lighting {
+ for light in lighting.punctual_lights.iter() {
+ let parameters = punctual_parameters(light, origin);
+ let high = parameters.first().ok_or_else(|| gpu("missing point-source origin"))?;
+ let low = parameters.get(1).ok_or_else(|| gpu("missing point-source origin residual"))?;
+ let point = Vec3::new(f64::from(high[0]), f64::from(high[1]), f64::from(high[2]));
+ let residual = Vec3::new(f64::from(low[0]), f64::from(low[1]), f64::from(low[2]));
+ let uncertainty = residual.len() + f64::from(epsilon);
+ for body in &scene.meshes {
+ if !closed(body.transmission) && !body.faces.iter().any(|face| closed(face.transmission)) {
+ continue;
+ }
+ for (ordinal, indices) in body.mesh.triangles.iter().enumerate() {
+ if ordinal % 256 == 0 {
+ cancel.check()?;
+ }
+ let mut points = [Vec3::ZERO; 3];
+ for (point, index) in points.iter_mut().zip(indices) {
+ let relative = *body.mesh.positions.get(*index as usize).ok_or_else(|| gpu("invalid photon optical vertex"))? - origin;
+ *point = Vec3::new(f64::from(relative.x as f32), f64::from(relative.y as f32), f64::from(relative.z as f32));
+ }
+ let bounds = points.into_iter().collect::<solidcraft_geom::Aabb3>();
+ if !bounds.inflated(uncertainty).contains(point) {
+ continue;
+ }
+ if let Ok(normal) = solidcraft_render::surface::unit_direction((points[1] - points[0]).cross(points[2] - points[0]))
+ && (point - points[0]).dot(normal).abs() <= uncertainty
+ {
+ return Err(JobError::new(
+ ErrorCode::InvalidScene,
+ "caustic point or spot origin is too close to a closed Glass boundary for unambiguous GPU medium classification",
+ ));
+ }
+ }
+ }
+ }
+ }
+ cancel.check()
+}
+
+pub(super) struct Pipelines {
+ pub(super) layout: wgpu::BindGroupLayout,
+ pub(super) render: wgpu::ComputePipeline,
+ clear: wgpu::ComputePipeline,
+ emit: wgpu::ComputePipeline,
+}
+impl Pipelines {
+ pub(super) fn shared(context: &Context) -> Result<&Self> {
+ if let Some(pipelines) = context.photons.get() {
+ return Ok(pipelines);
+ }
+ if context.device.limits().max_storage_buffers_per_shader_stage < 7 {
+ return Err(JobError::new(
+ ErrorCode::HostUnavailable,
+ "caustics require seven GPU storage buffers; ordinary GPU images remain available",
+ ));
+ }
+ let source = shader_source()?;
+ let compiling = one_compile_at_a_time();
+ let device = &context.device;
+ let scopes = scopes(device);
+ let module = device
+ .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("gpu-path caustics"), source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let entries: Vec<_> = (0..8)
+ .map(|binding| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: if binding == 0 {
+ wgpu::BufferBindingType::Uniform
+ } else {
+ wgpu::BufferBindingType::Storage { read_only: binding != 3 && binding != 6 && binding != 7 }
+ },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ })
+ .collect();
+ let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("gpu-path caustics"), entries: &entries });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("gpu-path caustics"),
+ bind_group_layouts: &[Some(&layout)],
+ immediate_size: 0,
+ });
+ let pipeline = |entry_point| {
+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some(entry_point),
+ layout: Some(&pipeline_layout),
+ module: &module,
+ entry_point: Some(entry_point),
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[("OPAQUE_SCENE", 0.0), ("HAS_TEXTURES", 1.0)],
+ ..Default::default()
+ },
+ cache: None,
+ })
+ };
+ let built = Self { render: pipeline("main"), clear: pipeline("photon_clear"), emit: pipeline("photon_emit"), layout };
+ checked(scopes)?;
+ drop(compiling);
+ let dummy = placeholder_bind(device, &built.layout, 8)?;
+ for pipeline in [&built.render, &built.clear, &built.emit] {
+ warm_up(device, &context.queue, pipeline, &dummy, &context.healthy)?;
+ }
+ Ok(context.photons.get_or_init(|| built))
+ }
+}
+pub(super) fn shader_source() -> Result<String> {
+ let base = SHADER.strip_suffix(DISABLED).ok_or_else(|| gpu("legacy path shader has no photon-disabled suffix"))?;
+ let mut source = String::new();
+ source
+ .try_reserve_exact(base.len() + PHOTONS.len())
+ .map_err(|_| JobError::new(ErrorCode::AllocationFailed, "caustic shader source allocation failed"))?;
+ source.push_str(base);
+ source.push_str(PHOTONS);
+ Ok(source)
+}
+
+pub(super) struct Resources {
+ pub(super) buffer: wgpu::Buffer,
+ pub(super) layout: wgpu::BindGroupLayout,
+ pub(super) render: wgpu::ComputePipeline,
+ clear: wgpu::ComputePipeline,
+ emit: wgpu::ComputePipeline,
+ photons: u32,
+ head_count: u32,
+ cleared: u32,
+ emitted: u32,
+ budget: dispatch::Budget,
+}
+impl Resources {
+ pub(super) fn new(context: &Context, options: CausticOptions, nodes: &[u8], source_count: u32) -> Result<Self> {
+ options.validate()?;
+ let head_count = heads(options)?;
+ let word = |index: usize| -> Result<u32> {
+ let begin = index.checked_mul(4).ok_or_else(|| gpu("caustic bounds offset overflow"))?;
+ let bytes: [u8; 4] =
+ nodes.get(begin..begin + 4).and_then(|bytes| bytes.try_into().ok()).ok_or_else(|| gpu("caustics require captured BVH bounds"))?;
+ Ok(u32::from_le_bytes(bytes))
+ };
+ let mut header = [0u32; HEADER_WORDS as usize];
+ header[0] = options.photons;
+ header[1] = head_count;
+ header[2] = (options.radius_mm as f32).to_bits();
+ header[3] = u32::from(options.max_depth);
+ header[4] = options.seed;
+ for (at, index) in [(6, 0), (7, 1), (8, 2), (9, 4), (10, 5), (11, 6)] {
+ let bits = word(index)?;
+ let coordinate = f32::from_bits(bits);
+ if !coordinate.is_finite() {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "caustics require finite captured BVH bounds"));
+ }
+ header[at] = bits;
+ }
+ for (lo, hi) in [(6, 9), (7, 10), (8, 11)] {
+ let span = f64::from(f32::from_bits(header[hi])) - f64::from(f32::from_bits(header[lo]));
+ if !(0.0..=1_048_576.0).contains(&(span / options.radius_mm)) {
+ return Err(JobError::new(
+ ErrorCode::InvalidRequest,
+ "caustic grid exceeds 2^20 radius cells along an axis; increase the radius explicitly",
+ ));
+ }
+ }
+ header[12] = source_count;
+ let mut bytes = [0u8; HEADER_WORDS as usize * 4];
+ for (word, output) in header.into_iter().zip(bytes.as_chunks_mut::<4>().0) {
+ output.copy_from_slice(&word.to_le_bytes());
+ }
+ let pipelines = Pipelines::shared(context)?;
+ let buffer = checked_creation(&context.device, || {
+ let buffer = context.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("caustic photons and spatial hash"),
+ size: buffer_bytes(options)?,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ context.queue.write_buffer(&buffer, 0, &bytes);
+ Ok(buffer)
+ })?;
+ Ok(Self {
+ buffer,
+ layout: pipelines.layout.clone(),
+ render: pipelines.render.clone(),
+ clear: pipelines.clear.clone(),
+ emit: pipelines.emit.clone(),
+ photons: options.photons,
+ head_count,
+ cleared: 0,
+ emitted: 0,
+ budget: Default::default(),
+ })
+ }
+ /// Some native drivers specialize a pipeline at its first dispatch for the
+ /// actual buffer bindings. The shared placeholder warm-up cannot establish
+ /// that this job's admitted resources have completed that setup. Zero work
+ /// warms every entry point under the existing setup timeout, without touching
+ /// photon heads/records, camera film, or either production controller.
+ pub(super) fn warm_up_actual(&self, context: &Context, uniform: &wgpu::Buffer, bind: &wgpu::BindGroup, cancel: &CancelToken) -> Result<()> {
+ cancel.check()?;
+ context.ensure_available()?;
+ checked_creation(&context.device, || {
+ context.queue.write_buffer(uniform, 0, &[0; PARAMETER_BYTES]);
+ Ok(())
+ })?;
+ for pipeline in [&self.render, &self.clear, &self.emit] {
+ cancel.check()?;
+ warm_up(&context.device, &context.queue, pipeline, bind, &context.healthy)?;
+ cancel.check()?;
+ }
+ Ok(())
+ }
+ pub(super) fn ready(&self) -> bool {
+ self.emitted == self.photons
+ }
+ pub(super) fn count(&self) -> u32 {
+ let remaining =
+ if self.cleared < self.head_count + self.photons { self.head_count + self.photons - self.cleared } else { self.photons - self.emitted };
+ self.budget.count(remaining)
+ }
+ pub(super) fn progress(&self) -> Progress {
+ Progress { phase: Phase::Preparing, done: u64::from(self.cleared + self.emitted), total: u64::from(self.head_count + 2 * self.photons) }
+ }
+ pub(super) fn step(
+ &mut self,
+ context: &Context,
+ uniform: &wgpu::Buffer,
+ bind: &wgpu::BindGroup,
+ parameters: &[u8],
+ cancel: &CancelToken,
+ ) -> Result<()> {
+ cancel.check()?;
+ context.ensure_available()?;
+ if self.ready() {
+ return Err(gpu("caustic prepass is already complete"));
+ }
+ let clearing = self.cleared < self.head_count + self.photons;
+ let offset = if clearing { self.cleared } else { self.emitted };
+ let count = self.count();
+ let started = Instant::now();
+ let scopes = scopes(&context.device);
+ context.queue.write_buffer(&self.buffer, 5 * 4, &offset.to_le_bytes());
+ context.queue.write_buffer(uniform, 0, parameters);
+ let mut encoder = context.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("caustic photon quantum") });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("caustic photon quantum"), timestamp_writes: None });
+ pass.set_pipeline(if clearing { &self.clear } else { &self.emit });
+ pass.set_bind_group(0, bind, &[]);
+ pass.dispatch_workgroups(count.div_ceil(PATH_WORKGROUP_SIZE), 1, 1);
+ }
+ let submission = context.queue.submit([encoder.finish()]);
+ checked(scopes)?;
+ context.wait(submission, TIMEOUT)?;
+ self.budget.observe(count, started.elapsed());
+ if clearing {
+ self.cleared += count;
+ if self.cleared == self.head_count + self.photons {
+ // Clearing is much cheaper than light paths; emission starts
+ // with the original tiny measured controller, never its peak.
+ self.budget = Default::default();
+ }
+ } else {
+ self.emitted += count;
+ }
+ cancel.check()
+ }
+ #[cfg(test)]
+ pub(super) fn maximum_quanta(&self) -> u32 {
+ (self.head_count + 2 * self.photons).div_ceil(dispatch::MIN_PATHS) + 2
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn photon_allocation_counts_exact_header_hash_records_and_upload() {
+ assert_eq!(admission_bytes(None).unwrap(), 0);
+ for photons in [1, 17, 16384, 65536] {
+ let options = CausticOptions { photons, ..Default::default() };
+ let head_count = heads(options).unwrap();
+ assert!(head_count.is_power_of_two() && head_count >= 2 * photons);
+ assert_eq!(buffer_bytes(options).unwrap(), 64 + u64::from(head_count) * 4 + u64::from(photons) * 64);
+ assert_eq!(admission_bytes(Some(options)).unwrap(), buffer_bytes(options).unwrap() + 64);
+ }
+ assert!(buffer_bytes(CausticOptions { photons: u32::MAX, ..Default::default() }).is_err());
+ }
+ #[test]
+ fn photon_shader_variant_preserves_the_legacy_six_buffer_source() {
+ assert!(!SHADER.contains("@binding(7)"));
+ let caustic = shader_source().unwrap();
+ assert!(caustic.contains("@binding(7)"));
+ assert!(caustic.contains("fn photon_emit") && caustic.contains("fn photon_clear"));
+ naga::front::wgsl::parse_str(&caustic).unwrap();
+ }
+}
diff --git a/crates/gpu/src/path/photons.wgsl b/crates/gpu/src/path/photons.wgsl
new file mode 100644
index 0000000000..867d14de76
--- /dev/null
+++ b/crates/gpu/src/path/photons.wgsl
@@ -0,0 +1,298 @@
+// Bounded light tracing for delta-source caustics. Finite sources already have
+// camera-path estimators and are deliberately absent from this source mixture.
+// Header16 words, hash heads, then16-word immutable photon records.
+@group(0) @binding(7) var<storage,read_write> photon_data:array<atomic<u32>>;
+fn photon_word(index:u32)->u32 {return atomicLoad(&photon_data[index]);}
+fn photon_float(index:u32)->f32 {return bitcast<f32>(photon_word(index));}
+fn photon_vector(index:u32)->vec3<f32> {return vec3<f32>(photon_float(index),photon_float(index+1u),photon_float(index+2u));}
+fn photon_store_vector(index:u32,value:vec3<f32>) {
+ atomicStore(&photon_data[index],bitcast<u32>(value.x));
+ atomicStore(&photon_data[index+1u],bitcast<u32>(value.y));
+ atomicStore(&photon_data[index+2u],bitcast<u32>(value.z));
+}
+fn photon_cell(position:vec3<f32>)->vec3<i32> {
+ return vec3<i32>(floor((position-photon_vector(6u))/photon_float(2u)));
+}
+fn photon_hash(cell:vec3<i32>)->u32 {
+ let words=bitcast<vec3<u32>>(cell);
+ return ((words.x*73856093u)^(words.y*19349663u)^(words.z*83492791u))&(photon_word(1u)-1u);
+}
+fn photon_record(index:u32)->u32 {return 16u+photon_word(1u)+index*16u;}
+fn photon_bad_medium() {atomicOr(&failures[7],4u);}
+fn photon_deposit(index:u32,position:vec3<f32>,incoming:vec3<f32>,flux:vec3<f32>,normal:vec3<f32>,receiver:u32,kind:u32,side:i32,source:u32) {
+ let record=photon_record(index);
+ photon_store_vector(record,position);photon_store_vector(record+4u,incoming);
+ photon_store_vector(record+8u,flux);photon_store_vector(record+12u,normal);
+ atomicStore(&photon_data[record+7u],receiver);atomicStore(&photon_data[record+11u],kind);
+ let side_code=select(select(0u,1u,side>0),2u,side<0);
+ atomicStore(&photon_data[record+15u],side_code|(source<<2u));
+ let previous=atomicExchange(&photon_data[16u+photon_hash(photon_cell(position))],index);
+ atomicStore(&photon_data[record+3u],previous);
+}
+// One uniformly selected eligible receiver per emitted path. Final multiplication
+// by the bounded visit count preserves every receiver's expected power without
+// allocating photons*depth records. The separate RNG never changes transport.
+struct PhotonReservoir {
+ visits:u32,rng:u32,position:vec3<f32>,incoming:vec3<f32>,flux:vec3<f32>,normal:vec3<f32>,receiver:u32,kind:u32,side:i32,
+ source:vec3<f32>,source_low:vec3<f32>,minimum:f32,source_index:u32,
+};
+fn photon_offer(reservoir:ptr<function,PhotonReservoir>,point:PrecisePoint,incoming:vec3<f32>,flux:vec3<f32>,normal:vec3<f32>,receiver:u32,kind:u32,side:i32) {
+ if (*reservoir).minimum>0.0 && length(precise_point_delta(point.hi,point.lo,(*reservoir).source,(*reservoir).source_low))<(*reservoir).minimum {punctual_count(0u);return;}
+ if !all(flux>=vec3<f32>(0.0)) || !all(flux<=vec3<f32>(3.4e38)) {atomicOr(&failures[7],1u);return;}
+ if !any(flux>vec3<f32>(0.0)) {return;}
+ (*reservoir).visits+=1u;
+ let count=(*reservoir).visits;
+ // Naga30's SPIR-V writer cannot cache a pointer-to-field call argument
+ // introduced in a short-circuit branch. Keep the same draws in a local RNG.
+ var selected=count==1u;
+ if count>1u {
+ var selection_rng=(*reservoir).rng;
+ selected=random(&selection_rng)<1.0/f32(count);
+ (*reservoir).rng=selection_rng;
+ }
+ if selected {
+ (*reservoir).position=point.hi+point.lo;(*reservoir).incoming=incoming;(*reservoir).flux=flux;
+ (*reservoir).normal=normal;(*reservoir).receiver=receiver;(*reservoir).kind=kind;(*reservoir).side=side;
+ }
+}
+@compute @workgroup_size(32)
+fn photon_clear(@builtin(global_invocation_id) invocation:vec3<u32>) {
+ if invocation.x>=u.sampling.z {return;}
+ let index=photon_word(5u)+invocation.x;let heads=photon_word(1u);
+ if index<heads {atomicStore(&photon_data[16u+index],0xffffffffu);}
+ else if index<heads+photon_word(0u) {atomicStore(&photon_data[photon_record(index-heads)+11u],0u);}
+}
+fn photon_unit_sphere(rng:ptr<function,u32>)->vec3<f32> {
+ let z=1.0-2.0*random(rng);let phi=2.0*PI*random(rng);let r=sqrt(max(0.0,1.0-z*z));
+ return vec3<f32>(r*cos(phi),r*sin(phi),z);
+}
+@compute @workgroup_size(32)
+fn photon_emit(@builtin(global_invocation_id) invocation:vec3<u32>) {
+ if invocation.x>=u.sampling.z {return;}
+ let index=photon_word(5u)+invocation.x;let count=photon_word(0u);
+ if index>=count {return;}
+ var reservoir:PhotonReservoir;
+ reservoir.rng=index^(photon_word(4u)*0x85ebca6bu)^0x6b8b4567u;
+ photon_trace(index,&reservoir);
+ if reservoir.visits>0u {
+ let flux=reservoir.flux*f32(reservoir.visits);
+ if !all(flux>=vec3<f32>(0.0)) || !all(flux<=vec3<f32>(3.4e38)) {atomicOr(&failures[7],1u);return;}
+ photon_deposit(index,reservoir.position,reservoir.incoming,flux,reservoir.normal,reservoir.receiver,reservoir.kind,reservoir.side,reservoir.source_index);
+ }
+}
+fn photon_trace(index:u32,reservoir:ptr<function,PhotonReservoir>) {
+ let count=photon_word(0u);
+ var rng=index^(photon_word(4u)*0x9e3779b9u)^0x8da6b343u;
+ let studio=u.environment.w>0.0;
+ let directions=select(3u,u32(u.light_count.x),studio);
+ let punctual=select(0u,u32(u.light_count.y),studio);
+ let sources=directions+punctual;
+ if sources==0u {return;}
+ let selected=min(sources-1u,u32(random(&rng)*f32(sources)));
+ (*reservoir).source_index=select(0u,selected-directions+1u,selected>=directions);
+ var origin=vec3<f32>(0.0);var origin_low=vec3<f32>(0.0);
+ var direction=vec3<f32>(0.0,0.0,-1.0);var flux=vec3<f32>(0.0);
+ var source_minimum=0.0;
+ if selected<directions {
+ var toward=FIXED_LIGHTS[min(selected,2u)].xyz;
+ var irradiance=vec3<f32>(FIXED_LIGHTS[min(selected,2u)].w*u.lighting.z*u.studio_weights[min(selected,2u)]);
+ if studio {let light=u.directional_lights[min(selected,7u)];toward=light.direction.xyz;irradiance=light.color.xyz*light.direction.w;}
+ direction=-toward;
+ let center=(photon_vector(6u)+photon_vector(9u))*0.5;
+ let radius=length(photon_vector(9u)-photon_vector(6u))*0.5;
+ if !(radius>0.0) {return;}
+ let axis=select(vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,1.0,0.0),abs(direction.z)>0.9);
+ let x=unit(cross(axis,direction));let y=cross(direction,x);
+ let r=radius*sqrt(random(&rng));let phi=2.0*PI*random(&rng);
+ origin=center-direction*(radius+max(u.lighting.x*2.0,radius*0.000001))+r*(cos(phi)*x+sin(phi)*y);
+ flux=irradiance*(PI*radius*radius*f32(sources)/f32(count));
+ } else {
+ let light=u.punctual_lights[min(selected-min(selected,directions),7u)];
+ origin=light.position.xyz;origin_low=light.position_low.xyz;source_minimum=light.position_low.w;
+ var density=1.0/(4.0*PI);var cone=1.0;
+ if light.cone.y>0.0 {
+ let cosine=1.0-random(&rng)*(1.0-light.cone.x);let phi=2.0*PI*random(&rng);
+ let sine=sqrt(max(0.0,1.0-cosine*cosine));
+ direction=from_local(vec3<f32>(sine*cos(phi),sine*sin(phi),cosine),light.axis.xyz);
+ density=1.0/(2.0*PI*(1.0-light.cone.x));
+ let blend=clamp((cosine-light.cone.x)/(light.axis.w-light.cone.x),0.0,1.0);
+ cone=blend*blend*(3.0-2.0*blend);
+ } else {direction=photon_unit_sphere(&rng);}
+ flux=light.color.xyz*(light.color.w*light.position.w*light.position.w*cone*f32(sources)/(density*f32(count)));
+ }
+ if !any(flux>vec3<f32>(0.0)) {return;}
+ var wavelength=0.0;
+ if (geometry[2]&0x40000000u)!=0u {
+ let channel=min(2u,u32(random(&rng)*3.0));wavelength=glass_wavelength(channel);
+ var mask=vec3<f32>(0.0);mask[channel]=3.0;flux*=mask;
+ }
+ transport_wavelength=wavelength;
+ let source_position=origin;let source_position_low=origin_low;
+ (*reservoir).source=source_position;(*reservoir).source_low=source_position_low;(*reservoir).minimum=source_minimum;
+ var media:array<Medium,MEDIUM_CAPACITY>;var medium_count=0u;
+ let first=origin_boundary(origin+origin_low,direction);
+ if !first.valid {photon_bad_medium();return;}
+ if first.hit.triangle!=0xffffffffu && !initialize_media_spectral(first.hit.triangle,direction,&media,&medium_count,wavelength) {photon_bad_medium();return;}
+ var previous=origin;var previous_low=origin_low;var excluded=0xffffffffu;var minimum=0.0;var optical=false;
+ let maximum=photon_word(3u);
+ for(var depth=0u;depth<maximum;depth+=1u) {
+ let hit=trace_precise(origin,origin_low,direction,false,excluded,minimum,medium_count>0u);
+ let emitter=emitter_hit_precise(origin,origin_low,direction,minimum);
+ if medium_count>0u && media[medium_count-1u].scatter.x>0.0 {
+ let current=media[medium_count-1u];let flight=-log(1.0-random(&rng))/current.scatter.x;
+ if flight<min(hit.distance,emitter.distance) {
+ let point=origin+origin_low+direction*flight;
+ flux*=exp(-current.sigma*length(precise_point_delta(point,vec3<f32>(0.0),previous,previous_low)));
+ if optical {photon_offer(reservoir,PrecisePoint(point,vec3<f32>(0.0)),-direction,flux,vec3<f32>(0.0),bitcast<u32>(current.id),3u,0);}
+ direction=sample_hg(direction,current.scatter.y,&rng);
+ // Rounded free-flight positions must remain in the same certified
+ // chain. Reuse its existing stack; never move a point to fit it.
+ let expected=medium_count;let expected_top=current.id;
+ let collision=origin_boundary(point,direction);
+ if !collision.valid || collision.hit.triangle==0xffffffffu {photon_bad_medium();return;}
+ if !initialize_media_spectral(collision.hit.triangle,direction,&media,&medium_count,wavelength) {photon_bad_medium();return;}
+ if medium_count!=expected || media[medium_count-1u].id!=expected_top {photon_bad_medium();return;}
+ origin=point;origin_low=vec3<f32>(0.0);
+ previous=point;previous_low=vec3<f32>(0.0);excluded=0xffffffffu;minimum=0.0;optical=true;continue;
+ }
+ }
+ if emitter.distance<hit.distance {return;}
+ if hit.triangle==0xffffffffu {if medium_count>0u {photon_bad_medium();}return;}
+ let t=triangle(hit.triangle);let point=surface_point_precise(t,hit.bary);
+ let outward=unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));let entering=dot(outward,direction)<0.0;
+ let geometric=select(-outward,outward,entering);
+ if medium_count>0u {flux*=exp(-media[medium_count-1u].sigma*length(precise_point_delta(point.hi,point.lo,previous,previous_low)));}
+ if !all(flux>=vec3<f32>(0.0)) || !all(flux<=vec3<f32>(3.4e38)) {atomicOr(&failures[7],1u);return;}
+ if !any(flux>vec3<f32>(0.0)) {return;}
+ if t.base.w<=0.0 {
+ if optical {photon_offer(reservoir,point,-direction,flux,geometric,hit.triangle,1u,0);}
+ return;
+ }
+ var normal=unit(t.n0.xyz*hit.bary.x+t.n1.xyz*hit.bary.y+t.n2.xyz*hit.bary.z);
+ if dot(normal,geometric)<0.0 {normal=-normal;}
+ if dot(normal,-direction)<=0.0 {normal=geometric;}
+ // All light tracing belongs to the reciprocal physical-normal mode.
+ normal=geometric;
+ var ni=1.0;if medium_count>0u {ni=media[medium_count-1u].ior;}
+ var nt=glass_ior(t.parameters.z,t.glass.y,wavelength);
+ if t.parameters.w>=0.0 {
+ if medium_count>0u {photon_bad_medium();return;}
+ if glass_rough_active(t,ni,nt) {
+ normal=glass_macro_normal(direction,normal,geometric,ni,nt);
+ var internal=false;var escaped=false;
+ for(var event=0u;event<maximum-depth;event+=1u) {
+ let macro_normal=select(-normal,normal,dot(direction,normal)<0.0);
+ let virtual_geometric=select(-geometric,geometric,dot(direction,normal)<0.0);
+ let face_outward=select(virtual_geometric,-virtual_geometric,internal);
+ let side=select(-1,1,dot(face_outward,outward)>0.0);
+ if optical {photon_offer(reservoir,point,-direction,flux,outward,hit.triangle,2u,side);}
+ let incident_ior=select(ni,nt,internal);let next_ior=select(nt,ni,internal);
+ let sampled=glass_interface(t,direction,macro_normal,virtual_geometric,incident_ior,next_ior,wavelength,false,0u,1u,&rng);
+ if !sampled.valid {return;}
+ flux*=sampled.weight;
+ direction=sampled.direction;optical=true;
+ if (!internal && !sampled.transmitted) || (internal && sampled.transmitted) {depth+=event;escaped=true;break;}
+ internal=true;let cosine=abs(dot(direction,normal));
+ if cosine==0.0 {return;}
+ if t.parameters.w>0.0 {flux*=exp(-t.optics.xyz*(t.parameters.w/cosine));}
+ }
+ if !escaped || dot(direction,normal)*dot(direction,geometric)<=0.0 {return;}
+ } else {
+ var f=dielectric(clamp(dot(normal,-direction),0.0,1.0),ni,nt);
+ let bent=refract(direction,normal,ni/nt);
+ if (f.z>=0.0 && dot(bent,geometric)>=0.0) || dot(reflect(direction,normal),geometric)<=0.0 {normal=geometric;f=dielectric(clamp(dot(normal,-direction),0.0,1.0),ni,nt);}
+ let weights=glass_sheet(t,f,clamp(dot(normal,-direction),0.0,1.0),ni,nt,wavelength);
+ let r=dot(weights.reflection,vec3<f32>(1.0/3.0));let tr=dot(weights.transmission,vec3<f32>(1.0/3.0));
+ if r+tr<=0.0 {return;}let probability=r/(r+tr);
+ if random(&rng)<probability {let outgoing=reflect(direction,normal);flux*=weights.reflection/probability;direction=outgoing;optical=true;}
+ else {flux*=weights.transmission/(1.0-probability);optical=optical || t.coat.w<=0.0;}
+ }
+ origin=point.hi+point.lo+direction*(u.lighting.x*2.0);origin_low=vec3<f32>(0.0);excluded=0xffffffffu;minimum=u.lighting.x;
+ } else {
+ if entering {
+ var parent=0.0;if t.interior.w>0.0 {parent=triangle(max(u32(t.interior.w),1u)-1u).optics.w;}
+ var actual=0.0;if medium_count>0u {actual=media[medium_count-1u].id;}
+ if parent!=actual {photon_bad_medium();return;}
+ } else {
+ if medium_count==0u || media[medium_count-1u].id!=t.optics.w {photon_bad_medium();return;}
+ nt=1.0;if medium_count>1u {nt=media[medium_count-2u].ior;}
+ }
+ // Geometric-normal fallback matches smooth camera transport before
+ // drawing a visible rough normal. Wrong-side rough samples are null.
+ normal=glass_macro_normal(direction,normal,geometric,ni,nt);
+ if optical && glass_rough_active(t,ni,nt) {photon_offer(reservoir,point,-direction,flux,outward,hit.triangle,2u,0);}
+ let sampled=glass_interface(t,direction,normal,geometric,ni,nt,wavelength,false,0u,1u,&rng);
+ if !sampled.valid {return;}
+ flux*=sampled.weight;direction=sampled.direction;optical=true;
+ if sampled.transmitted {
+ if entering {
+ if medium_count>=MEDIUM_CAPACITY {photon_bad_medium();return;}
+ media[medium_count]=Medium(t.optics.w,nt,t.optics.xyz,t.interior.xy);medium_count+=1u;
+ } else {medium_count-=1u;}
+ }
+ if abs(dot(direction,geometric))<1e-6 {return;}
+ origin=point.hi;origin_low=point.lo;excluded=hit.triangle;minimum=0.0;
+ }
+ previous=point.hi;previous_low=point.lo;
+ }
+}
+fn photon_gather(t:Triangle,position:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,view:vec3<f32>) -> vec3<f32> {
+ let count=photon_word(0u);if count==0u || t.base.w>0.0 {return vec3<f32>(0.0);}
+ let radius=photon_float(2u);let center=photon_cell(position);var result=vec3<f32>(0.0);
+ for(var z=-1;z<=1;z+=1) {for(var y=-1;y<=1;y+=1) {for(var x=-1;x<=1;x+=1) {
+ let cell=center+vec3<i32>(x,y,z);var index=photon_word(16u+photon_hash(cell));var visited=0u;
+ loop {
+ if index==0xffffffffu || index>=count || visited>=count {break;}visited+=1u;
+ let record=photon_record(index);let point=photon_vector(record);let delta=point-position;
+ if photon_word(record+11u)==1u && photon_receiver_allowed(record,position) && all(photon_cell(point)==cell) && dot(delta,delta)<=radius*radius && abs(dot(delta,geometric))<=radius*0.1 && dot(photon_vector(record+12u),geometric)>0.0 && triangle(min(photon_word(record+7u),max(geometry[0],1u)-1u)).optics.w==t.optics.w {
+ let incoming=photon_vector(record+4u);
+ if dot(incoming,normal)>0.0 && dot(incoming,geometric)>0.0 {result+=brdf(t,normal,view,incoming)*photon_vector(record+8u)*(dot(incoming,normal)/dot(incoming,geometric));}
+ }
+ index=photon_word(record+3u);
+ }
+ }}}
+ return result/(PI*radius*radius);
+}
+fn photon_enabled()->bool {return photon_word(0u)>0u;}
+fn photon_receiver_allowed(record:u32,position:vec3<f32>)->bool {
+ let source=photon_word(record+15u)>>2u;
+ if source==0u {return true;}
+ if source>u32(u.light_count.y) {return false;}
+ let light=u.punctual_lights[min(max(source,1u)-1u,7u)];
+ return length(precise_point_delta(position,vec3<f32>(0.0),light.position.xyz,light.position_low.xyz))>=light.position_low.w;
+}
+fn photon_gather_glass(t:Triangle,position:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,incident:vec3<f32>,ni:f32,nt:f32,wavelength:f32,side:i32)->vec3<f32> {
+ let count=photon_word(0u);if count==0u {return vec3<f32>(0.0);}
+ let radius=photon_float(2u);let center=photon_cell(position);var result=vec3<f32>(0.0);
+ let outward=unit(cross(t.p1.xyz-t.p0.xyz,t.p2.xyz-t.p0.xyz));
+ for(var z=-1;z<=1;z+=1) {for(var y=-1;y<=1;y+=1) {for(var x=-1;x<=1;x+=1) {
+ let cell=center+vec3<i32>(x,y,z);var index=photon_word(16u+photon_hash(cell));var visited=0u;
+ loop {
+ if index==0xffffffffu || index>=count || visited>=count {break;}visited+=1u;
+ let record=photon_record(index);let point=photon_vector(record);let delta=point-position;
+ let side_code=select(select(0u,1u,side>0),2u,side<0);
+ if photon_word(record+11u)==2u && (photon_word(record+15u)&3u)==side_code && photon_receiver_allowed(record,position) && all(photon_cell(point)==cell) && dot(delta,delta)<=radius*radius && abs(dot(delta,outward))<=radius*0.1 && dot(photon_vector(record+12u),outward)>0.0 && triangle(min(photon_word(record+7u),max(geometry[0],1u)-1u)).optics.w==t.optics.w {
+ let incoming=photon_vector(record+4u);let projected=abs(dot(incoming,geometric));
+ if projected>0.0 {result+=glass_evaluate_cosine(t.glass,incident,incoming,normal,geometric,ni,nt,wavelength)*photon_vector(record+8u)/projected;}
+ }
+ index=photon_word(record+3u);
+ }
+ }}}
+ return result/(PI*radius*radius);
+}
+fn photon_gather_volume(position:vec3<f32>,incident:vec3<f32>,medium:Medium)->vec3<f32> {
+ let count=photon_word(0u);if count==0u || medium.scatter.x<=0.0 {return vec3<f32>(0.0);}
+ let radius=photon_float(2u);let center=photon_cell(position);var result=vec3<f32>(0.0);
+ for(var z=-1;z<=1;z+=1) {for(var y=-1;y<=1;y+=1) {for(var x=-1;x<=1;x+=1) {
+ let cell=center+vec3<i32>(x,y,z);var index=photon_word(16u+photon_hash(cell));var visited=0u;
+ loop {
+ if index==0xffffffffu || index>=count || visited>=count {break;}visited+=1u;
+ let record=photon_record(index);let point=photon_vector(record);let delta=point-position;
+ if photon_word(record+11u)==3u && photon_word(record+7u)==bitcast<u32>(medium.id) && photon_receiver_allowed(record,position) && all(photon_cell(point)==cell) && dot(delta,delta)<=radius*radius {
+ result+=photon_vector(record+8u)*glass_hg_phase(dot(incident,photon_vector(record+4u)),medium.scatter.y);
+ }
+ index=photon_word(record+3u);
+ }
+ }}}
+ return result*(3.0/(4.0*PI*radius*radius*radius*medium.scatter.x));
+}
diff --git a/crates/gpu/src/path/photons_disabled.wgsl b/crates/gpu/src/path/photons_disabled.wgsl
new file mode 100644
index 0000000000..5fd521cdf1
--- /dev/null
+++ b/crates/gpu/src/path/photons_disabled.wgsl
@@ -0,0 +1,7 @@
+// Legacy jobs retain their six-storage-buffer pipeline and own no photon map.
+fn photon_gather(t:Triangle,position:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,view:vec3<f32>) -> vec3<f32> {
+ return vec3<f32>(0.0);
+}
+fn photon_enabled()->bool {return false;}
+fn photon_gather_glass(t:Triangle,position:vec3<f32>,normal:vec3<f32>,geometric:vec3<f32>,incident:vec3<f32>,ni:f32,nt:f32,wavelength:f32,side:i32)->vec3<f32> {return vec3<f32>(0.0);}
+fn photon_gather_volume(position:vec3<f32>,incident:vec3<f32>,medium:Medium)->vec3<f32> {return vec3<f32>(0.0);}
diff --git a/crates/gpu/src/path/scene.rs b/crates/gpu/src/path/scene.rs
index c08e6734a8..7a4571c0a7 100644
--- a/crates/gpu/src/path/scene.rs
+++ b/crates/gpu/src/path/scene.rs
@@ -21,6 +21,13 @@ pub(super) struct Triangle {
pub scalar_face: bool,
}
type MediumEdge = (usize, usize, i32);
+// The material header word reserves the high two bits for model lanes and wavelength sampling.
+pub(super) const MATERIAL_OFFSET_MASK: u32 = 0x3fff_ffff;
+
+pub(super) fn model_bytes_per_triangle(scene: &ProductScene) -> u64 {
+ let modeled = |t: Option<Transmission>| t.is_some_and(|t| t.model().is_some());
+ if scene.meshes.iter().any(|m| modeled(m.transmission) || m.faces.iter().any(|f| modeled(f.transmission))) { 16 } else { 0 }
+}
pub(super) fn medium_preparation_bytes(scene: &ProductScene) -> u64 {
// Validation consumes one body's scratch at a time. Opaque/thin-sheet bodies
// allocate none of the weld table: do not charge their triangles for it.
@@ -63,6 +70,7 @@ pub(super) struct Upload {
pub geometry: Vec<u8>,
pub nodes: Vec<u8>,
pub epsilon: f32,
+ pub active_glass_model: bool,
}
fn invalid(message: &str) -> JobError {
@@ -79,6 +87,19 @@ pub(super) fn flatten(scene: &ProductScene, origin: Vec3, cancel: &CancelToken)
flatten_with_media(scene, origin, cancel, false)
}
pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &CancelToken, nested: bool) -> Result<Upload> {
+ let model_bytes = model_bytes_per_triangle(scene) as usize;
+ let material_bytes = 80 + model_bytes;
+ let mut material_flags = if model_bytes > 0 { 0x80000000 } else { 0 };
+ let mut active_glass_model = false;
+ let transmissions =
+ scene.meshes.iter().flat_map(|body| std::iter::once(body.transmission).chain(body.faces.iter().map(|face| face.transmission)));
+ for model in transmissions.filter_map(|transmission| transmission.and_then(Transmission::model)) {
+ active_glass_model |= !model.is_identity();
+ if model.spectral() {
+ material_flags |= 0x40000000;
+ break;
+ }
+ }
let count = scene.meshes.iter().map(|m| m.mesh.triangles.len()).sum::<usize>();
let mut triangles = reserved(count)?;
let vertex_count = scene.meshes.iter().map(|m| m.mesh.positions.len()).sum::<usize>();
@@ -88,6 +109,7 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
for (body_index, body) in scene.meshes.iter().enumerate() {
cancel.check()?;
let body_start = triangles.len();
+ let mut authored_optical = false;
let mut faces = reserved(body.faces.len())?;
faces.extend(body.faces.iter());
faces.sort_unstable_by_key(|f| f.face);
@@ -118,6 +140,7 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
let look = faces.binary_search_by_key(&face, |f| f.face).ok().and_then(|i| faces.get(i));
let opacity = look.map_or(body.opacity, |f| f.opacity);
let transmission = look.map_or(body.transmission, |f| f.transmission);
+ authored_optical |= transmission.is_some();
if opacity != 1.0 && transmission.is_none() {
return Err(invalid("gpu-path requires explicit transmission for nonopaque preview appearances"));
}
@@ -144,6 +167,10 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
}
}
if (p[1] - p[0]).cross(p[2] - p[0]).len() <= 1e-12 {
+ // Preserve the historical source-degenerate pole-face skip for
+ // both sheets and solids. The optical target must retain faces,
+ // every retained face must survive upload, and closed targets
+ // still require the complete source and uploaded shell proofs.
continue;
}
if let Some(t) = transmission
@@ -151,6 +178,19 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
{
t.with_subsurface(scatter).map_err(|e| invalid(&e.to_string()))?;
}
+ if let Some(model) = transmission.and_then(|t| t.model()) {
+ model.validate(surface.dielectric_ior()).map_err(|e| invalid(&e.to_string()))?;
+ let roughness = model.roughness as f32;
+ let alpha = roughness * roughness;
+ if model.roughness > 0.0 && (alpha * alpha < f32::MIN_POSITIVE || !(1.0_f32 / (std::f32::consts::PI * alpha * alpha)).is_finite()) {
+ return Err(invalid("authored glass roughness is below GPU microfacet arithmetic precision"));
+ }
+ }
+ if transmission
+ .is_some_and(|t| t.model().is_some_and(|m| m.roughness > 0.0) && t.thin_wall_thickness_mm().is_some() && t.shadow_transmission())
+ {
+ return Err(invalid("rough thin-sheet glass requires disabled straight shadow transmission"));
+ }
if transmission.is_some() && surface.clear_coat().is_some() {
return Err(invalid("clear coat and transmission cannot share a surface"));
}
@@ -166,6 +206,21 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
scalar_face: look.is_some(),
});
}
+ if authored_optical && !triangles[body_start..].iter().any(|t| t.transmission.is_some()) {
+ return Err(invalid("glass boundary has no nondegenerate optical triangles"));
+ }
+ validate_medium(&triangles[body_start..], cancel)?;
+ // Prove the boundary actually sent to the shader as well as the source
+ // seam topology. Rounding must not close an authored gap, collapse a
+ // valid face, reverse its orientation or break its uploaded shell.
+ for (index, triangle) in triangles[body_start..].iter_mut().enumerate() {
+ if index % 1024 == 0 {
+ cancel.check()?;
+ }
+ if triangle.transmission.is_some() {
+ triangle.p = uploaded_optical_positions(triangle.p)?;
+ }
+ }
validate_medium(&triangles[body_start..], cancel)?;
let body_triangles = &triangles[body_start..];
if body_triangles.iter().any(|t| t.transmission.is_some()) {
@@ -203,12 +258,16 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
}
let patches = planar_patches::ids(&triangles, cancel)?;
let extent = nodes.first().map_or(1.0, |n| n.lo.iter().zip(n.hi).map(|(a, b)| b - a).fold(0.0f32, f32::max));
- let mut geometry = reserved(16 + triangles.len().max(1) * 100 + vertices.len())?;
- let mut materials = reserved(triangles.len().max(1) * 80)?;
+ let mut geometry = reserved(16 + triangles.len().max(1) * (100 + model_bytes) + vertices.len())?;
+ let mut materials = reserved(triangles.len().max(1) * material_bytes)?;
let vertex_word = 4 + triangles.len().max(1) * 4;
let material_word = vertex_word + vertices.len() / 4;
- let patch_word = material_word + triangles.len().max(1) * 20;
- for word in [triangles.len() as u32, vertex_word as u32, material_word as u32, patch_word as u32] {
+ let patch_word = material_word + triangles.len().max(1) * (material_bytes / 4);
+ let material_word = u32::try_from(material_word)
+ .ok()
+ .filter(|word| word & !MATERIAL_OFFSET_MASK == 0)
+ .ok_or_else(|| invalid("material table offset exceeds its packed geometry layout"))?;
+ for word in [triangles.len() as u32, vertex_word as u32, material_word | material_flags, patch_word as u32] {
geometry.extend_from_slice(&word.to_le_bytes());
}
for (material, t) in triangles.into_iter().enumerate() {
@@ -248,10 +307,22 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
),
parent_triangle as f32,
);
+ if model_bytes > 0 {
+ let model = t.transmission.and_then(|t| t.model());
+ vector(
+ &mut materials,
+ Vec3::new(
+ model.map_or(0.0, |m| m.roughness),
+ model.and_then(|m| m.dispersion).map_or(0.0, |d| d.abbe_number),
+ model.and_then(|m| m.thin_film).map_or(0.0, |f| f.thickness_nm),
+ ),
+ model.and_then(|m| m.thin_film).map_or(0.0, |f| f.ior) as f32,
+ );
+ }
}
if geometry.len() == 16 {
geometry.resize(32, 0);
- materials.resize(80, 0);
+ materials.resize(material_bytes, 0);
}
geometry.extend_from_slice(&vertices);
drop(vertices);
@@ -278,7 +349,26 @@ pub(super) fn flatten_with_media(scene: &ProductScene, origin: Vec3, cancel: &Ca
}
node_bytes.extend_from_slice(&node.count.to_le_bytes());
}
- Ok(Upload { geometry, nodes: node_bytes, epsilon: (extent * 1e-7).max(1e-5) })
+ Ok(Upload { geometry, nodes: node_bytes, epsilon: (extent * 1e-7).max(1e-5), active_glass_model })
+}
+
+fn uploaded_optical_positions(source: [Vec3; 3]) -> Result<[Vec3; 3]> {
+ let stored = source.map(|p| Vec3::new(f64::from(p.x as f32), f64::from(p.y as f32), f64::from(p.z as f32)));
+ let original_normal = (source[1] - source[0]).cross(source[2] - source[0]);
+ let stored_normal = (stored[1] - stored[0]).cross(stored[2] - stored[0]);
+ let [a, b, c] = stored.map(|p| [p.x as f32, p.y as f32, p.z as f32]);
+ let u: [f32; 3] = std::array::from_fn(|i| b[i] - a[i]);
+ let v: [f32; 3] = std::array::from_fn(|i| c[i] - a[i]);
+ let shader_normal = Vec3::new(f64::from(u[1] * v[2] - u[2] * v[1]), f64::from(u[2] * v[0] - u[0] * v[2]), f64::from(u[0] * v[1] - u[1] * v[0]));
+ if !stored.iter().all(|p| p.is_finite())
+ || stored_normal.len() == 0.0
+ || original_normal.dot(stored_normal) <= 0.0
+ || !shader_normal.is_finite()
+ || stored_normal.dot(shader_normal) <= 0.0
+ {
+ return Err(invalid("glass triangle collapses or reverses orientation at camera-relative GPU position precision"));
+ }
+ Ok(stored)
}
const MEDIUM_WELD_MM: f64 = 1e-6;
@@ -402,12 +492,70 @@ fn validate_medium(triangles: &[Triangle], cancel: &CancelToken) -> Result<()> {
return Err(invalid("closed dielectric body must contain exactly one connected shell"));
}
}
+ validate_vertex_links(&mut edges, &mut parents, cancel)?;
if six_volume <= 0.0 || !six_volume.is_finite() {
return Err(invalid("glass mesh must enclose positive outward-oriented volume"));
}
cancel.check()
}
+// Reuse the already prepaid edge and face-component scratch. Each matched edge
+// supplies one outgoing corner at either endpoint and the adjacent face there.
+// In a two-manifold each vertex's incident faces form one circular link; a
+// pinched vertex has multiple links even when every edge and the shell pass.
+fn validate_vertex_links(edges: &mut [MediumEdge], parents: &mut [usize], cancel: &CancelToken) -> Result<()> {
+ for (index, edge) in edges.as_chunks_mut::<2>().0.iter_mut().enumerate() {
+ if index % 1024 == 0 {
+ cancel.check()?;
+ }
+ let [a, b] = edge;
+ let first = *a;
+ let second = *b;
+ *a = (if first.2 > 0 { first.0 } else { first.1 }, second.2.unsigned_abs() as usize - 1, first.2.unsigned_abs() as i32);
+ *b = (if second.2 > 0 { second.0 } else { second.1 }, first.2.unsigned_abs() as usize - 1, second.2.unsigned_abs() as i32);
+ }
+ edges.sort_unstable();
+ let mut start = 0;
+ while start < edges.len() {
+ cancel.check()?;
+ let vertex = edges.get(start).ok_or_else(|| invalid("missing glass vertex link"))?.0;
+ let mut end = start + 1;
+ while edges.get(end).is_some_and(|e| e.0 == vertex) {
+ if end % 1024 == 0 {
+ cancel.check()?;
+ }
+ end += 1;
+ }
+ let link = edges.get(start..end).ok_or_else(|| invalid("invalid glass vertex-link range"))?;
+ for (index, edge) in link.iter().enumerate() {
+ if index % 1024 == 0 {
+ cancel.check()?;
+ }
+ let face = edge.2 as usize - 1;
+ *parents.get_mut(face).ok_or_else(|| invalid("invalid glass vertex-link face"))? = face;
+ }
+ for (index, edge) in link.iter().enumerate() {
+ if index % 1024 == 0 {
+ cancel.check()?;
+ }
+ let first = medium_root(parents, edge.2 as usize - 1)?;
+ let second = medium_root(parents, edge.1)?;
+ *parents.get_mut(first).ok_or_else(|| invalid("invalid glass vertex-link component"))? = second;
+ }
+ let root = medium_root(parents, link.first().ok_or_else(|| invalid("empty glass vertex link"))?.2 as usize - 1)?;
+ for (index, edge) in link.iter().enumerate() {
+ if index % 1024 == 0 {
+ cancel.check()?;
+ }
+ if medium_root(parents, edge.2 as usize - 1)? != root {
+ return Err(invalid("closed glass vertex link must be one connected circular fan; pinched boundaries are unsupported"));
+ }
+ }
+ start = end;
+ }
+ cancel.check()
+}
+
fn medium_root(parents: &mut [usize], mut index: usize) -> Result<usize> {
loop {
let parent = *parents.get(index).ok_or_else(|| invalid("invalid glass component index"))?;
diff --git a/crates/gpu/src/path/scene_weld_tests.rs b/crates/gpu/src/path/scene_weld_tests.rs
index 360781c5d4..ef40e8041d 100644
--- a/crates/gpu/src/path/scene_weld_tests.rs
+++ b/crates/gpu/src/path/scene_weld_tests.rs
@@ -87,3 +87,106 @@ fn weld_scratch_only_counts_the_largest_closed_medium() {
two.meshes.push(glass.meshes[0].clone());
assert_eq!(medium_preparation_bytes(&two), medium_preparation_bytes(&glass) + triangle_bytes);
}
+
+#[test]
+fn optical_upload_refuses_collapsed_and_reversed_faces_but_preserves_rebased_geometry() {
+ let origin = Vec3::new(1_000_000.0, 0.0, 0.0);
+ let mut source = seam_tetra(Vec3::ZERO);
+ let mesh = Arc::make_mut(&mut source.meshes[0].mesh);
+ mesh.positions = vec![origin, origin + Vec3::X * 0.01, origin + Vec3::Y * 0.01, origin + Vec3::Z * 0.01, origin];
+ source.bounds = source.meshes[0].mesh.bounds();
+ let cancel = CancelToken::default();
+ let error = flatten(&source, Vec3::ZERO, &cancel).err().unwrap();
+ assert!(error.message.contains("GPU position precision"), "{error}");
+ assert!(flatten(&source, origin, &cancel).is_ok(), "camera-relative representable tetrahedron must retain its closed boundary");
+
+ let mesh = Arc::make_mut(&mut source.meshes[0].mesh);
+ mesh.positions =
+ vec![Vec3::new(1_000_000.36, 1_000_000.29, 0.0), Vec3::new(1_000_000.33, 1_000_000.10, 0.0), Vec3::new(1_000_000.44, 1_000_000.56, 0.0)];
+ mesh.normals = vec![Vec3::Z; 3];
+ mesh.triangles = vec![[0, 1, 2]];
+ mesh.tri_face = vec![0];
+ source.meshes[0].transmission = Some(Transmission::new(Vec3::ZERO, Some(0.0)).unwrap());
+ source.bounds = source.meshes[0].mesh.bounds();
+ let error = flatten(&source, Vec3::ZERO, &cancel).err().unwrap();
+ assert!(error.message.contains("reverses orientation"), "f64-positive area becomes f32-negative area: {error}");
+ assert!(flatten(&source, Vec3::new(1_000_000.0, 1_000_000.0, 0.0), &cancel).is_ok());
+}
+
+#[test]
+fn degenerate_optical_boundaries_refuse_without_erasing_redundant_pole_compatibility() {
+ let cancel = CancelToken::default();
+ let mut source = seam_tetra(Vec3::ZERO);
+ // A redundant pole face does not alter the certified remaining shell.
+ let mesh = Arc::make_mut(&mut source.meshes[0].mesh);
+ mesh.triangles.push([0, 0, 1]);
+ mesh.tri_face.push(0);
+ assert!(flatten(&source, Vec3::ZERO, &cancel).is_ok());
+ source.meshes[0].transmission = Some(Transmission::new(Vec3::ZERO, Some(0.5)).unwrap());
+ assert!(flatten(&source, Vec3::ZERO, &cancel).is_ok(), "redundant source pole faces retain thin-sheet compatibility too");
+ let mesh = Arc::make_mut(&mut source.meshes[0].mesh);
+ mesh.triangles = vec![[0, 0, 1]];
+ mesh.tri_face = vec![0];
+ for thickness in [None, Some(0.5)] {
+ source.meshes[0].transmission = Some(Transmission::new(Vec3::ZERO, thickness).unwrap());
+ let error = flatten(&source, Vec3::ZERO, &cancel).err().unwrap();
+ assert!(error.message.contains("no nondegenerate optical triangles"), "{error}");
+ }
+ source.meshes[0].transmission = None;
+ assert!(flatten(&source, Vec3::ZERO, &cancel).is_ok(), "opaque degenerate skipping is unchanged");
+}
+
+#[test]
+fn closed_glass_refuses_a_pinched_vertex_even_when_edges_and_global_connectivity_pass() {
+ let mut source = seam_tetra(Vec3::ZERO);
+ let mesh = Arc::make_mut(&mut source.meshes[0].mesh);
+ mesh.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 { 2.0 }))
+ .collect();
+ mesh.triangles.clear();
+ for face in [[0, 2, 3, 1], [4, 5, 7, 6], [0, 4, 6, 2], [1, 3, 7, 5], [0, 1, 5, 4], [2, 6, 7, 3]] {
+ let center = face.map(|i| mesh.positions[i]).into_iter().fold(Vec3::ZERO, |a, b| a + b) * 0.25;
+ let index = mesh.positions.len() as u32;
+ mesh.positions.push(center);
+ for corner in 0..4 {
+ mesh.triangles.push([index, face[corner] as u32, face[(corner + 1) % 4] as u32]);
+ }
+ }
+ mesh.normals = vec![Vec3::Z; mesh.positions.len()];
+ mesh.tri_face = vec![0; mesh.triangles.len()];
+ source.bounds = mesh.bounds();
+ let cancel = CancelToken::default();
+ assert!(flatten(&source, Vec3::ZERO, &cancel).is_ok());
+ let pinch = source.meshes[0].mesh.positions[0];
+ Arc::make_mut(&mut source.meshes[0].mesh).positions[7] = pinch;
+ let error = flatten(&source, Vec3::ZERO, &cancel).err().unwrap();
+ assert!(error.message.contains("vertex link"), "{error}");
+}
+
+#[test]
+fn optional_glass_material_lane_grows_only_authored_uploads() {
+ use solidcraft_render::glass_model::{Dispersion, GlassModel, ThinFilm};
+ let cancel = CancelToken::default();
+ let plain = seam_tetra(Vec3::ZERO);
+ let original = flatten(&plain, Vec3::ZERO, &cancel).unwrap();
+ let word = |bytes: &[u8], index: usize| u32::from_le_bytes(bytes[index * 4..index * 4 + 4].try_into().unwrap());
+ let mask = super::MATERIAL_OFFSET_MASK;
+ assert_eq!(word(&original.geometry, 2) & !mask, 0);
+ assert!(!original.active_glass_model);
+ assert_eq!(super::model_bytes_per_triangle(&plain), 0);
+ for (model, flags, active) in [
+ (GlassModel::default(), 0x80000000, false),
+ (GlassModel { thin_film: Some(ThinFilm { ior: 1.38, thickness_nm: 0.0 }), ..Default::default() }, 0x80000000, false),
+ (GlassModel { roughness: 0.35, ..Default::default() }, 0x80000000, true),
+ (GlassModel { dispersion: Some(Dispersion { abbe_number: 50.0 }), ..Default::default() }, 0xc0000000, true),
+ ] {
+ let mut modeled = plain.clone();
+ modeled.meshes[0].transmission = Some(modeled.meshes[0].transmission.unwrap().with_model(model).unwrap());
+ let uploaded = flatten(&modeled, Vec3::ZERO, &cancel).unwrap();
+ assert_eq!(uploaded.geometry.len(), original.geometry.len() + plain.meshes[0].mesh.triangles.len() * 16);
+ assert_eq!(word(&uploaded.geometry, 2) & !mask, flags, "model={model:?}");
+ assert_eq!(word(&uploaded.geometry, 2) & mask, word(&original.geometry, 2));
+ assert_eq!(uploaded.active_glass_model, active, "model={model:?}");
+ assert_eq!(super::model_bytes_per_triangle(&modeled), 16);
+ }
+}
diff --git a/crates/gpu/src/path/shadows.wgsl b/crates/gpu/src/path/shadows.wgsl
index 6f28d1040e..d0fd53fea0 100644
--- a/crates/gpu/src/path/shadows.wgsl
+++ b/crates/gpu/src/path/shadows.wgsl
@@ -8,13 +8,21 @@ fn shadow_transmittance(origin: vec3<f32>, origin_low: vec3<f32>, direction: vec
var result = ShadowResult(vec3<f32>(1.0),1.0,0u,false);
var o = origin;
var o_low = origin_low;
- var ray_excluded = 0xffffffffu;
- var ray_minimum = minimum;
- var medium_id = 0.0;
- var medium_ior = 1.0;
- var sigma = vec3<f32>(0.0);
+ let boundary_connection=GLASS_DELTA_LIGHTS && transport_boundary_connection;
+ var ray_excluded = select(0xffffffffu,transport_source_triangle,transport_medium_id!=0.0 || boundary_connection);
+ var ray_minimum = select(minimum,0.0,transport_medium_id!=0.0 || boundary_connection);
+ var medium_id = transport_medium_id;
+ var medium_ior = transport_medium_ior;
+ let initial_ior=medium_ior;
+ let geometric_normals=glass_geometric_normals();
+ // Smooth legacy connections keep the scale of the optional straight-solid
+ // approximation. A contained segment still cancels its equal endpoint IORs.
+ let physical_scale=GLASS_DELTA_LIGHTS || geometric_normals;
+ var sigma = transport_medium_sigma;
+ var scatter=transport_medium_scatter;
var entry = origin;
var entry_low = origin_low;
+ if medium_id!=0.0 {entry=transport_connection_origin;entry_low=transport_connection_origin_low;}
// Up to 64 interfaces. If traversal cannot establish visibility, block it.
for (var step=0u; step<=64u; step+=1u) {
let traversed = dot(precise_point_delta(o,o_low,origin,origin_low),direction);
@@ -24,18 +32,26 @@ fn shadow_transmittance(origin: vec3<f32>, origin_low: vec3<f32>, direction: vec
let hit = trace_precise_within(o,o_low,direction,false,ray_excluded,ray_minimum,medium_id!=0.0,select(FAR,remaining,medium_id==0.0),remaining);
if hit.triangle == 0xffffffffu {
if medium_id!=0.0 { return blocked_shadow(); }
+ if !result.solid || physical_scale {result.transmittance*=initial_ior*initial_ior;}
return result;
}
if hit.distance>=remaining {
// A finite emitter may be inside a certified medium. Attenuate only
// to that emitter, never to the body's farther exit surface.
- if medium_id!=0.0 { result.transmittance*=exp(-sigma*length(ray_segment_precise(o,o_low,entry,entry_low,direction,remaining)))/(medium_ior*medium_ior); }
+ if medium_id!=0.0 {
+ let distance=length(ray_segment_precise(o,o_low,entry,entry_low,direction,remaining));
+ let survival=exp(-scatter*distance);
+ result.transmittance*=exp(-sigma*distance)*survival/(medium_ior*medium_ior);
+ result.branch_pdf*=survival;
+ }
+ if !result.solid || physical_scale {result.transmittance*=initial_ior*initial_ior;}
return result;
}
if step==64u { return blocked_shadow(); }
if OPAQUE_SCENE {return blocked_shadow();}
let t = triangle(hit.triangle);
if t.base.w<=0.0 || t.coat.w<=0.0 { return blocked_shadow(); }
+ let optical_ior=glass_ior(t.parameters.z,t.glass.y,transport_wavelength);
var position=surface_point(t,hit.bary);
var position_low=vec3<f32>(0.0);
if t.parameters.w<0.0 {
@@ -48,16 +64,17 @@ fn shadow_transmittance(origin: vec3<f32>, origin_low: vec3<f32>, direction: vec
var n=unit(t.n0.xyz*hit.bary.x+t.n1.xyz*hit.bary.y+t.n2.xyz*hit.bary.z);
if dot(n,geometric)<0.0 { n=-n; }
if dot(n,-direction)<=0.0 { n=geometric; }
+ if geometric_normals {n=geometric;}
if t.parameters.w>=0.0 {
if medium_id!=0.0 { return blocked_shadow(); }
// Match the primary path's shading-normal fallback before the sheet sum.
- var f=dielectric(clamp(dot(n,-direction),0.0,1.0),1.0,t.parameters.z);
- let refracted=refract(direction,n,1.0/t.parameters.z);
+ var f=dielectric(clamp(dot(n,-direction),0.0,1.0),1.0,optical_ior);
+ let refracted=refract(direction,n,1.0/optical_ior);
if (f.z>=0.0 && dot(refracted,geometric)>=0.0) || dot(reflect(direction,n),geometric)<=0.0 {
n=geometric;
- f=dielectric(clamp(dot(n,-direction),0.0,1.0),1.0,t.parameters.z);
+ f=dielectric(clamp(dot(n,-direction),0.0,1.0),1.0,optical_ior);
}
- let weights=sheet(t,f);
+ let weights=glass_sheet(t,f,clamp(dot(n,-direction),0.0,1.0),1.0,optical_ior,transport_wavelength);
let r=dot(weights.reflection,vec3<f32>(1.0/3.0));
let tr=dot(weights.transmission,vec3<f32>(1.0/3.0));
if r+tr<=0.0 || tr<=0.0 { return blocked_shadow(); }
@@ -67,19 +84,22 @@ fn shadow_transmittance(origin: vec3<f32>, origin_low: vec3<f32>, direction: vec
result.solid=true;
// Reciprocal external-angle Fresnel at each surface. Applying an
// inside critical angle to this unrefracted connection would invent TIR.
- let f=dielectric(clamp(abs(dot(outward,direction)),0.0,1.0),1.0,t.parameters.z);
- result.transmittance*=1.0-(f.x+f.y)*0.5;
+ let reflection=glass_reflection(t,clamp(abs(dot(outward,direction)),0.0,1.0),1.0,optical_ior,transport_wavelength);
+ result.transmittance*=vec3<f32>(1.0)-reflection;
if entering {
if medium_id!=0.0 { return blocked_shadow(); }
- medium_id=t.optics.w; medium_ior=t.parameters.z; entry=position; entry_low=position_low; sigma=t.optics.xyz;
+ medium_id=t.optics.w; medium_ior=optical_ior; entry=position; entry_low=position_low; sigma=t.optics.xyz;scatter=t.interior.x;
} else {
// The first crossing from the shading point exits a closed body:
// the point touches or lies within it (see the path loop).
if medium_id==0.0 && step==0u {
- medium_id=t.optics.w; medium_ior=t.parameters.z; sigma=t.optics.xyz; entry=origin; entry_low=origin_low;
+ medium_id=t.optics.w; medium_ior=optical_ior; sigma=t.optics.xyz; entry=origin; entry_low=origin_low;scatter=t.interior.x;
}
if medium_id==0.0 || medium_id!=t.optics.w { return blocked_shadow(); }
- result.transmittance*=exp(-sigma*length(precise_point_delta(position,position_low,entry,entry_low)));
+ let distance=length(precise_point_delta(position,position_low,entry,entry_low));
+ let survival=exp(-scatter*distance);
+ result.transmittance*=exp(-sigma*distance)*survival;
+ result.branch_pdf*=survival;
medium_id=0.0;
}
}
diff --git a/crates/gpu/src/path/tests.rs b/crates/gpu/src/path/tests.rs
index 195b67c106..44f22acaf0 100644
--- a/crates/gpu/src/path/tests.rs
+++ b/crates/gpu/src/path/tests.rs
@@ -173,6 +173,1402 @@ fn gpu_exact_dielectric_matches_f64_fresnel() {
}
}
+#[test]
+fn gpu_sheet_grazing_and_zero_thickness_match_physical_path_limits() {
+ let Some(executor) = executor() else { return };
+ let context = &executor.context;
+ let source = format!(
+ "{SHADER}\n@compute @workgroup_size(1) fn sheet_limit_reference() {{
+ var t=triangle(0u);t.parameters.w=u.up.w;t.optics=vec4<f32>(u.right.xyz,t.optics.w);
+ let weights=sheet(t,dielectric(u.up.x,u.up.y,u.up.z));
+ accumulation[0]=vec4<f32>(weights.reflection,1.0);
+ accumulation[1]=vec4<f32>(weights.transmission,1.0);
+ }}"
+ );
+ let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&context.layout)],
+ immediate_size: 0,
+ });
+ let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("sheet_limit_reference"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let mut task = Task::new(context.clone(), glass_slab(true), request(2), JobOptions::default(), CancelToken::default()).unwrap();
+ for (ni, nt) in [(1.0, 1.0), (1.0, 1.5)] {
+ for thickness in [0.0, 0.7] {
+ for cosine in [0.0, 0.0001, 0.6, 1.0] {
+ for sigma in [Vec3::ZERO, Vec3::new(0.5, 1.0, 0.0)] {
+ let mut params = vec![0; 48];
+ scene::vector(&mut params, sigma, 0.0);
+ scene::vector(&mut params, Vec3::new(cosine, ni, nt), thickness as f32);
+ params.resize(PARAMETER_BYTES, 0);
+ context.queue.write_buffer(&task.uniform, 0, &params);
+ context.queue.write_buffer(&task.failures, 0, &[0; FAILURE_BYTES as usize]);
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ if ni == nt && thickness > 0.0 && cosine == 0.0 {
+ let error = task.read_linear().unwrap_err();
+ assert_eq!(error.code, ErrorCode::InvalidScene);
+ assert!(error.message.contains("grazing optical path"), "{error}");
+ continue;
+ }
+ let pixels = task.read_linear().unwrap();
+ let optics = solidcraft_render::transmission::Transmission::new(sigma, Some(thickness)).unwrap();
+ let (reflection, transmission) = solidcraft_render::transmission::slab(optics, thickness, cosine, ni, nt).unwrap();
+ for (pixel, expected) in pixels.iter().take(2).zip([reflection, transmission]) {
+ for (actual, expected) in pixel.iter().zip([expected.x, expected.y, expected.z]) {
+ assert!(
+ (f64::from(*actual) - expected).abs() < 3e-5,
+ "{ni}->{nt}, thickness={thickness}, cosine={cosine}: {pixel:?} != {expected}"
+ );
+ }
+ }
+ if ni == nt && thickness == 0.0 {
+ assert_eq!(pixels[0], [0.0, 0.0, 0.0, 1.0]);
+ assert_eq!(pixels[1], [1.0; 4], "no absorption path exists even with nonzero authored sigma");
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn optional_glass_gpu_film_dispersion_and_visible_normals_match_the_f64_oracle() {
+ use solidcraft_render::glass_model::{Dispersion, GlassModel, ThinFilm};
+ let Some(executor) = executor() else { return };
+ let context = &executor.context;
+ let source = format!(
+ "{SHADER}\n@compute @workgroup_size(1) fn glass_model_reference() {{
+ var t=triangle(0u);t.glass=u.lighting;
+ let f=glass_film(u.up.x,u.up.y,u.up.z,t.glass.w,t.glass.z,u.up.w);
+ accumulation[0]=vec4<f32>(f,glass_ior(u.up.z,t.glass.y,u.up.w),1.0);
+ var rng=u.sampling.x;
+ let event=glass_interface(t,-unit(u.back.xyz),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),u.up.y,u.up.z,u.up.w,true,0u,1u,&rng);
+ accumulation[1]=vec4<f32>(event.direction+vec3<f32>(2.0),select(0.0,1.0,event.valid));
+ accumulation[2]=vec4<f32>(event.weight,select(0.0,1.0,event.transmitted));
+ let bent=vec3<f32>(0.6,0.0,0.8);
+ let normal=glass_macro_normal(vec3<f32>(0.0,0.0,-1.0),bent,vec3<f32>(0.0,0.0,1.0),1.0,1.5);
+ accumulation[3]=vec4<f32>(normal,1.0);
+ }}"
+ );
+ let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&context.layout)],
+ immediate_size: 0,
+ });
+ let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("glass_model_reference"),
+ // HG-only jobs use this specialization with no active model or photons.
+ compilation_options: wgpu::PipelineCompilationOptions { constants: &[("GLASS_DELTA_LIGHTS", 1.0)], ..Default::default() },
+ cache: None,
+ });
+ let mut task = Task::new(context.clone(), glass_slab(true), request(2), JobOptions::default(), CancelToken::default()).unwrap();
+ let random = |state: &mut u32| {
+ *state = state.wrapping_mul(747796405).wrapping_add(2891336453);
+ let word = ((*state >> ((*state >> 28) + 4)) ^ *state).wrapping_mul(277803737);
+ f64::from((((word >> 22) ^ word) >> 8) as f32 * (1.0 / 16777216.0))
+ };
+ for model in [
+ GlassModel::default(),
+ GlassModel { roughness: 0.35, ..Default::default() },
+ GlassModel { roughness: 0.35, thin_film: Some(ThinFilm { ior: 1.38, thickness_nm: 380.0 }), ..Default::default() },
+ GlassModel { dispersion: Some(Dispersion { abbe_number: 25.0 }), ..Default::default() },
+ ] {
+ for (ni, nt) in [(1.0, 1.5), (1.5, 1.0), (1.5, 1.5)] {
+ for cosine in [0.35_f64, 1.0] {
+ for wavelength in [460.0, 550.0, 610.0] {
+ let view = Vec3::new(f64::from(((1.0 - cosine * cosine).sqrt()) as f32), 0.0, f64::from(cosine as f32));
+ let mut params = vec![0; PARAMETER_BYTES];
+ params[16..20].copy_from_slice(&71_u32.to_le_bytes());
+ let mut vector = Vec::new();
+ scene::vector(&mut vector, Vec3::new(cosine, ni, nt), wavelength as f32);
+ scene::vector(&mut vector, view, 0.0);
+ scene::vector(
+ &mut vector,
+ Vec3::new(model.roughness, model.dispersion.map_or(0.0, |d| d.abbe_number), model.thin_film.map_or(0.0, |f| f.thickness_nm)),
+ model.thin_film.map_or(0.0, |f| f.ior) as f32,
+ );
+ params[64..112].copy_from_slice(&vector);
+ context.queue.write_buffer(&task.uniform, 0, &params);
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ let pixels = task.read_linear().unwrap();
+ assert_eq!(pixels[3], [0.6, 0.0, 0.8, 1.0], "HG-only lighting retains a valid bent shading normal");
+ let bare = model.fresnel(f64::from(cosine as f32), ni, nt, wavelength).unwrap();
+ for (actual, expected) in pixels[0].iter().zip([bare.s, bare.p, model.ior(nt, wavelength).unwrap()]) {
+ assert!(
+ (f64::from(*actual) - expected).abs() < 5e-4,
+ "model={model:?}, {ni}->{nt}, cosine={cosine}, wavelength={wavelength}: {pixels:?} != {expected}"
+ );
+ }
+ let rough = model.roughness > 0.0 && !(ni == nt && model.thin_film.is_none_or(|f| f.thickness_nm == 0.0 || f.ior == ni));
+ let mut state = 71_u32;
+ let uniforms = if rough { [random(&mut state), random(&mut state), random(&mut state)] } else { [0.5, 0.5, random(&mut state)] };
+ let expected = model.sample(-view, Vec3::Z, ni, nt, wavelength, uniforms).unwrap();
+ if let Some(expected) = expected {
+ assert_eq!(pixels[1][3], 1.0, "{model:?}: {pixels:?}");
+ for (actual, expected) in
+ pixels[1].iter().zip([expected.direction.x + 2.0, expected.direction.y + 2.0, expected.direction.z + 2.0])
+ {
+ assert!((f64::from(*actual) - expected).abs() < 8e-4, "sampled direction differs: {model:?}: {pixels:?} != {expected}");
+ }
+ assert!(
+ (f64::from(pixels[2][0]) - expected.weight).abs() < 8e-4,
+ "sample weight differs: {model:?}: {pixels:?} != {expected:?}"
+ );
+ assert_eq!(pixels[2][3] != 0.0, expected.crosses);
+ } else {
+ assert_eq!(pixels[1][3], 0.0, "a rejected f64 visible-facet sample must not be retried: {model:?}: {pixels:?}");
+ }
+ }
+ }
+ }
+ }
+}
+
+fn rough_glass_fixture(thin: bool, roughness: f64, absorption: Vec3, scattering: f64) -> ProductScene {
+ let mut scene = glass_slab(thin);
+ let mut transmission = solidcraft_render::transmission::Transmission::new(absorption, thin.then_some(0.7))
+ .unwrap()
+ .with_shadow_transmission(false)
+ .with_model(solidcraft_render::glass_model::GlassModel { roughness, ..Default::default() })
+ .unwrap();
+ if scattering > 0.0 {
+ transmission = transmission
+ .with_subsurface(solidcraft_render::transmission::subsurface::Subsurface { scattering_per_mm: scattering, anisotropy: 0.3 })
+ .unwrap();
+ }
+ scene.meshes[0].transmission = Some(transmission);
+ scene
+}
+
+fn rough_glass_pixel(context: Arc<Context>, scene: ProductScene, options: JobOptions) -> [f32; 4] {
+ let mut image = request(1);
+ image.camera.fov = 0.000001;
+ let expected_bytes = 16 * if options.adaptive.is_some() { 3 } else { 1 } + glass_tile_bytes(&scene, &image);
+ let mut task = Task::new(context, scene, image, options, CancelToken::default()).unwrap();
+ assert_eq!(task.accumulation.size(), expected_bytes, "optical scratch must be appended after exactly the historical film planes");
+ for _ in 0..options.samples {
+ task.complete_sample().unwrap();
+ }
+ task.read_linear().unwrap()[0]
+}
+
+#[test]
+fn optical_hard_light_specialization_ignores_identity_models_and_refuses_nonfinite_f32_ggx_peaks() {
+ assert!((1..=(1 << 24)).contains(&MAX_GPU_PATH_TRIANGLES), "captured parent references must remain exact f32 integers");
+ let identity = rough_glass_fixture(false, 0.0, Vec3::ZERO, 0.0);
+ assert!(!needs_glass_lighting(&identity));
+ assert_eq!(glass_tile_bytes(&identity, &request(1024)), 0);
+ let rough = rough_glass_fixture(false, 0.4, Vec3::ZERO, 0.0);
+ assert_eq!(glass_tile_bytes(&rough, &request(1)), 128);
+ assert_eq!(glass_tile_bytes(&rough, &request(128)), 128 * u64::from(dispatch::MAX_PATHS));
+ assert_eq!(glass_tile_bytes(&rough, &request(1024)), 128 * u64::from(dispatch::MAX_PATHS));
+ assert!(needs_glass_lighting(&rough_glass_fixture(false, 0.4, Vec3::ZERO, 0.0)));
+ assert!(needs_glass_lighting(&rough_glass_fixture(false, 0.0, Vec3::ZERO, 0.5)));
+ let representable = rough_glass_fixture(false, 1e-9, Vec3::ZERO, 0.0);
+ assert!(scene::flatten(&representable, Vec3::ZERO, &CancelToken::default()).is_ok());
+ for roughness in [1e-10, 3e-10] {
+ let overflow = rough_glass_fixture(false, roughness, Vec3::ZERO, 0.0);
+ let failure = scene::flatten(&overflow, Vec3::ZERO, &CancelToken::default()).err().unwrap();
+ assert!(failure.message.contains("roughness"), "{failure}");
+ }
+ let mut thin = rough_glass_fixture(true, 0.4, Vec3::ZERO, 0.0);
+ assert!(scene::flatten(&thin, Vec3::ZERO, &CancelToken::default()).is_ok());
+ thin.meshes[0].transmission = thin.meshes[0].transmission.map(|material| material.with_shadow_transmission(true));
+ assert!(
+ scene::flatten(&thin, Vec3::ZERO, &CancelToken::default()).is_err(),
+ "a straight shadow cannot stand in for independent rough interfaces"
+ );
+}
+
+#[test]
+fn rough_glass_hard_direction_point_spot_and_contained_transmission_match_analytic_projected_bsdf() {
+ use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights, PunctualLightOptions, PunctualLights, SpotConeOptions, StudioLighting};
+ let Some(executor) = executor() else { return };
+ let roughness = 0.5_f64;
+ // At normal incidence D=1/(pi*roughness^4), G=1 and F=.04.
+ let reflection = 0.04 / (4.0 * std::f64::consts::PI * roughness.powi(4));
+ let directional = StudioLighting {
+ directional_lights: DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }])
+ .unwrap(),
+ ..Default::default()
+ };
+ for thin in [false, true] {
+ for source in 0..3 {
+ let cone = (source == 2).then_some(SpotConeOptions {
+ emitted_axis: [0.0, 0.0, -1.0],
+ inner_half_angle_radians: 0.1,
+ outer_half_angle_radians: 0.4,
+ });
+ let lighting = if source == 0 {
+ directional
+ } else {
+ StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.0, 0.0, 4.0],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone,
+ }])
+ .unwrap(),
+ ..Default::default()
+ }
+ };
+ let options = JobOptions { samples: 1, max_depth: 1, lighting: Some(lighting), ..Default::default() };
+ let mut scene = rough_glass_fixture(thin, roughness, Vec3::ZERO, 0.0);
+ if source == 0 {
+ Arc::make_mut(&mut scene.meshes[0].mesh).normals.fill(Vec3::new(0.6, 0.0, 0.8));
+ }
+ let actual = rough_glass_pixel(executor.context.clone(), scene, options);
+ let expected = reflection / if source == 0 { 1.0 } else { 3.5_f64.powi(2) };
+ for value in actual.into_iter().take(3) {
+ assert!((f64::from(value) - expected).abs() < expected * 0.0002, "thin={thin}, source={source}: {actual:?} != {expected}");
+ }
+ assert_eq!(actual[3], 1.0);
+ }
+ }
+ // The point lies inside the slab, half a millimetre past its rough entry.
+ // Walter's normal-incidence BTDF*cos is (1-F)*ni^2*D/(nt-ni)^2.
+ let transmission = 0.96 / (0.5_f64.powi(2) * std::f64::consts::PI * roughness.powi(4));
+ let lighting = StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.0; 3],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ };
+ for scattering in [0.0, 0.6] {
+ let actual = rough_glass_pixel(
+ executor.context.clone(),
+ rough_glass_fixture(false, roughness, Vec3::new(0.2, 0.4, 0.8), scattering),
+ JobOptions { samples: 1, max_depth: 1, lighting: Some(lighting), ..Default::default() },
+ );
+ for (value, absorption) in actual.into_iter().take(3).zip([0.2, 0.4, 0.8]) {
+ let expected = transmission * 4.0 * (-0.5_f64 * (absorption + scattering)).exp();
+ assert!((f64::from(value) - expected).abs() < expected * 0.0003, "contained BTDF/Beer/HG {actual:?} != {expected}");
+ }
+ }
+ let inactive = rough_glass_pixel(
+ executor.context.clone(),
+ rough_glass_fixture(false, 0.0, Vec3::ZERO, 0.0),
+ JobOptions { samples: 1, max_depth: 1, lighting: Some(directional), ..Default::default() },
+ );
+ assert_eq!(inactive, [0.0, 0.0, 0.0, 1.0], "smooth delta glass has no continuous hard-light lobe");
+ for thin in [false, true] {
+ let render = |zero_source: bool| {
+ let directional_lights = if zero_source {
+ DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 0.0 }]).unwrap()
+ } else {
+ DirectionalLights::default()
+ };
+ rough_glass_pixel(
+ executor.context.clone(),
+ rough_glass_fixture(thin, 0.5, Vec3::new(0.2, 0.4, 0.8), 0.0),
+ JobOptions {
+ samples: 32,
+ max_depth: 16,
+ lighting: Some(StudioLighting { directional_lights, environment: [1.0; 3], ..Default::default() }),
+ ..Default::default()
+ },
+ )
+ };
+ let plain = render(false);
+ assert!(plain[0] > 0.0);
+ assert_eq!(plain, render(true), "offering zero-power NEE vertices must not advance the BSDF transport RNG: thin={thin}");
+ }
+ let mut image = request(1);
+ image.camera.target = Vec3::new(0.17, 0.07, 0.0);
+ image.camera.distance = 0.01;
+ image.camera.fov = 0.000001;
+ let options = JobOptions {
+ samples: 512,
+ max_depth: 1,
+ seed: 43,
+ nested_media: true,
+ lighting: Some(StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.17, 0.07, 0.25],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ let mut expected = 0.0;
+ let phase = 0.91 / (4.0 * std::f64::consts::PI * 1.69_f64.powf(1.5));
+ for ordinal in 0..options.samples {
+ let mut state = ordinal.wrapping_mul(0x9e3779b9) ^ options.seed;
+ let mut random = || {
+ state = state.wrapping_mul(747796405).wrapping_add(2891336453);
+ let word = ((state >> ((state >> 28) + 4)) ^ state).wrapping_mul(277803737);
+ f64::from((((word >> 22) ^ word) >> 8) as f32 * (1.0 / 16777216.0))
+ };
+ let _ = (random(), random()); // Independent primary AA dimensions.
+ let travel = -(1.0 - random()).ln() / 2.0;
+ if travel < 0.51 {
+ let distance = 0.24 + travel;
+ expected += phase * (-2.0 * distance).exp() / distance.powi(2) / f64::from(options.samples);
+ }
+ }
+ let mut task =
+ Task::new(executor.context.clone(), rough_glass_fixture(false, 0.0, Vec3::ZERO, 2.0), image, options, CancelToken::default()).unwrap();
+ for _ in 0..options.samples {
+ task.complete_sample().unwrap();
+ }
+ let actual = task.read_linear().unwrap()[0];
+ for value in actual.into_iter().take(3) {
+ assert!(
+ (f64::from(value) - expected).abs() < expected * 0.0003,
+ "primary selected HG must connect to its contained delta emitter: {actual:?} != {expected}"
+ );
+ }
+}
+
+#[test]
+fn rough_optical_two_phase_tiles_preserve_adaptive_strata_and_converged_film() {
+ use solidcraft_render::job::{DirectionalLightOptions, DirectionalLights, StudioLighting, adaptive::AdaptiveSampling};
+ let Some(executor) = executor() else { return };
+ let lighting = StudioLighting {
+ directional_lights: DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }])
+ .unwrap(),
+ ..Default::default()
+ };
+ let options = JobOptions {
+ samples: 32,
+ max_depth: 1,
+ seed: 1948,
+ transmission_samples: 4,
+ adaptive: Some(AdaptiveSampling { pilot_samples: 16, min_samples: 16, ..Default::default() }),
+ lighting: Some(lighting),
+ ..Default::default()
+ };
+ let mut image = request(17);
+ image.height = 19;
+ image.camera.fov = 0.000001;
+ let scene = rough_glass_fixture(false, 0.5, Vec3::ZERO, 0.0);
+ let pixels = u64::from(image.width) * u64::from(image.height);
+ let scratch = glass_tile_bytes(&scene, &image);
+ let mut task = Task::new(executor.context, scene, image, options, CancelToken::default()).unwrap();
+ assert_eq!(task.accumulation.size(), pixels * 48 + scratch);
+ let mut offset_seen = false;
+ while task.sample < 32 {
+ task.dispatch().unwrap();
+ offset_seen |= task.offset > 0;
+ }
+ assert!(offset_seen, "the physical control must exercise a nonzero tile offset");
+ let converged = task.read_linear().unwrap();
+ loop {
+ if matches!(task.step(4096).unwrap(), TaskPoll::Complete(_)) {
+ break;
+ }
+ }
+ let actual = task.read_linear().unwrap();
+ assert_eq!(actual, converged, "later maximum-budget iterations must skip both optical phases without touching converged film");
+ let expected = 0.04 / (4.0 * std::f64::consts::PI * 0.5_f64.powi(4));
+ for (pixel, value) in actual.iter().enumerate() {
+ assert_eq!(value[3], 1.0, "coverage at pixel{pixel}");
+ for channel in &value[..3] {
+ assert!(
+ (f64::from(*channel) - expected).abs() < expected * 0.0002,
+ "pilot/stratum film normalization at pixel{pixel}: {value:?} != {expected}"
+ );
+ }
+ }
+ let report = task.sampling_report().unwrap();
+ assert_eq!(report.pilot_samples_per_pixel, 16);
+ assert_eq!((report.minimum_production_samples, report.maximum_production_samples), (16, 16));
+ assert_eq!(report.production_samples, pixels * 16);
+ assert_eq!(report.transmission_strata, 4);
+ assert_eq!(report.primary_path_evaluations, pixels * (16 + 16 * 4));
+ assert_eq!(report.pixels_at_cap, 0);
+}
+
+fn rough_shadow_overlap_scene(shadow_transmission: bool) -> ProductScene {
+ let floor = ProductMesh {
+ name: "original unit-Lambert floor".into(),
+ mesh: Arc::new(Mesh {
+ positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)],
+ normals: vec![Vec3::Z; 4],
+ triangles: vec![[0, 1, 2], [0, 2, 3]],
+ tri_face: vec![0, 0],
+ ..Default::default()
+ }),
+ color: [255; 3],
+ opacity: 1.0,
+ surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 1.0, 1.0).unwrap()),
+ transmission: None,
+ faces: Vec::new(),
+ };
+ let mut glass = glass_slab(false).meshes.remove(0);
+ glass.name = "original off-axis rough closed box".into();
+ for point in &mut Arc::make_mut(&mut glass.mesh).positions {
+ *point = Vec3::new(2.0 + point.x * 0.1, point.y * 0.1, 1.0 + point.z * 1.4);
+ }
+ glass.transmission = Some(
+ solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None)
+ .unwrap()
+ .with_shadow_transmission(shadow_transmission)
+ .with_model(solidcraft_render::glass_model::GlassModel { roughness: 0.5, ..Default::default() })
+ .unwrap(),
+ );
+ let bounds = floor.mesh.bounds().union(&glass.mesh.bounds());
+ ProductScene { meshes: vec![floor, glass], bounds }
+}
+
+#[test]
+fn rough_closed_shadow_approximation_replaces_only_the_transmitted_hard_source_family() {
+ use solidcraft_render::job::{PunctualLightOptions, PunctualLights, StudioLighting};
+ let Some(executor) = executor() else { return };
+ let lighting = StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [2.0, 0.0, 1.0],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ };
+ let render = |shadow, depth| {
+ let options = JobOptions { samples: 512, seed: 1948, max_depth: depth, lighting: Some(lighting), ..Default::default() };
+ let mut image = request(1);
+ image.camera.fov = 0.000001;
+ let mut task = Task::new(executor.context.clone(), rough_shadow_overlap_scene(shadow), image, options, CancelToken::default()).unwrap();
+ for _ in 0..options.samples {
+ task.complete_sample().unwrap();
+ }
+ task.read_linear().unwrap()[0]
+ };
+ // The floor-to-point vector is (2,0,1), d=sqrt5, n_floor.l=1/sqrt5.
+ // Its first glass crossing is x=1,z=.5, with incident cosine2/sqrt5.
+ // Independent s/p Fresnel equations, then the existing straight-connection
+ // inside-emitter radiance conversion1/nt^2; no production Fresnel helper.
+ let cosine = 2.0 / 5.0_f64.sqrt();
+ let transmitted_cosine = (1.0 - (1.0 - cosine * cosine) / 1.5_f64.powi(2)).sqrt();
+ let rs = (cosine - 1.5 * transmitted_cosine) / (cosine + 1.5 * transmitted_cosine);
+ let rp = (1.5 * cosine - transmitted_cosine) / (1.5 * cosine + transmitted_cosine);
+ let reflection = 0.5 * (rs * rs + rp * rp);
+ let expected = (1.0 - reflection) / (2.25 * std::f64::consts::PI * 5.0 * 5.0_f64.sqrt());
+ let one = render(true, 1);
+ let two = render(true, 2);
+ for actual in [one, two] {
+ assert_eq!(actual[3], 1.0);
+ for channel in &actual[..3] {
+ assert!((f64::from(*channel) - expected).abs() < expected * 0.0002, "{actual:?} != {expected}");
+ }
+ }
+ assert_eq!(one, two, "another opaque->rough transmitted NEE must not duplicate the enabled straight approximation");
+ let blocked = render(false, 1);
+ assert_eq!(blocked, [0.0, 0.0, 0.0, 1.0]);
+ let physical = render(false, 2);
+ assert!(
+ physical[..3].iter().all(|v| v.is_finite() && *v > 0.0),
+ "a sampled rough hit must receive the contained hard point when its opaque straight connection is blocked: {physical:?}"
+ );
+ // The positive physical control above proves that this fixed stream really
+ // reaches the rough box; increasing SPP is not a substitute for this check.
+}
+
+#[test]
+fn reflection_only_closed_nee_packet_keeps_its_actual_inside_medium_beer() {
+ use solidcraft_render::job::{PunctualLightOptions, PunctualLights, StudioLighting};
+ let Some(executor) = executor() else { return };
+ let context = &executor.context;
+ let lighting = StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.13, -0.07, 0.0],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ };
+ let options = JobOptions { samples: 1, max_depth: 1, lighting: Some(lighting), ..Default::default() };
+ let mut scene = rough_glass_fixture(false, 0.5, Vec3::new(0.2, 0.4, 0.8), 0.0);
+ let optics = scene.meshes[0].transmission.unwrap();
+ scene.meshes[0].transmission = Some(optics.with_shadow_transmission(true));
+ let mut task = Task::new(context.clone(), scene, request(1), options, CancelToken::default()).unwrap();
+ let source=format!("{SHADER}\n@compute @workgroup_size(1) fn closed_reflection_medium_reference() {{
+ if u.sampling.z==0u {{return;}}
+ let hit=trace_precise(vec3<f32>(0.13,-0.07,-2.0),vec3<f32>(0.0),vec3<f32>(0.0,0.0,1.0),false,0xffffffffu,0.0,false);
+ var payload:array<vec4<u32>,6>;var count=0u;var selection_rng=81u;
+ glass_offer_light(&payload,&count,&selection_rng,PrecisePoint(vec3<f32>(0.13,-0.07,-0.5),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,-1.0),vec3<f32>(1.0),1.5,1.0,hit.triangle,4u,glass_vacuum());
+ accumulation[0]=vec4<f32>(glass_resolve_light(&payload,count,0.0),1.0);
+ }}");
+ let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&context.layout)],
+ immediate_size: 0,
+ });
+ let constants = [("GLASS_DELTA_LIGHTS", 1.0)];
+ let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("closed_reflection_medium_reference"),
+ compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },
+ cache: None,
+ });
+ context.queue.write_buffer(&task.uniform, 0, &[0; PARAMETER_BYTES]);
+ warm_up(&context.device, &context.queue, &pipeline, &task.bind, &context.healthy).unwrap();
+ context.queue.write_buffer(&task.uniform, 0, &task.parameters(1).unwrap());
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ let actual = task.read_linear().unwrap()[0];
+ let response = 0.04 / (4.0 * std::f64::consts::PI * 0.5_f64.powi(4));
+ for (value, absorption) in actual.into_iter().take(3).zip([0.2, 0.4, 0.8]) {
+ let expected = response * 4.0 * (-0.5_f64 * absorption).exp();
+ assert!(
+ (f64::from(value) - expected).abs() < expected * 0.0003,
+ "inside reflection requires its actual medium, not sheet/vacuum metadata: {actual:?} != {expected}"
+ );
+ }
+ assert_eq!(actual[3], 1.0);
+}
+
+#[test]
+fn rough_closed_and_virtual_sheet_photon_partition_keeps_primary_caustics_and_avoids_double_counting() {
+ use solidcraft_render::job::{CausticOptions, DirectionalLightOptions, DirectionalLights, StudioLighting};
+ let Some(executor) = executor() else { return };
+ if executor.context.device.limits().max_storage_buffers_per_shader_stage < 7 {
+ return;
+ }
+ let lighting = StudioLighting {
+ directional_lights: DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, -1.0], color: [1.0; 3], intensity: 1.0 }])
+ .unwrap(),
+ ..Default::default()
+ };
+ for thin in [false, true] {
+ let render = |map: bool, depth: u32| {
+ rough_glass_pixel(
+ executor.context.clone(),
+ rough_glass_fixture(thin, 0.45, Vec3::ZERO, 0.0),
+ JobOptions {
+ samples: 32,
+ max_depth: depth,
+ lighting: Some(lighting),
+ caustics: map.then_some(CausticOptions { photons: 8192, radius_mm: 2.0, max_depth: 8, seed: 81 }),
+ ..Default::default()
+ },
+ )
+ };
+ let one = render(false, 1);
+ let two = render(false, 2);
+ assert_eq!(one, [0.0, 0.0, 0.0, 1.0], "the first interface cannot connect directly to an exterior backlight");
+ assert!(two[0] > 0.0 && two[0].is_finite(), "map-off virtual/closed exit must receive a hard backlight: thin={thin}, {two:?}");
+ // Hold one immutable photon map fixed across both camera depths. Two
+ // independent parallel prepasses can sum a cell's atomic-linked records
+ // in different orders and differ by an ULP, unrelated to path partition.
+ let mapped_options = JobOptions {
+ samples: 32,
+ seed: 1948,
+ max_depth: 2,
+ lighting: Some(lighting),
+ caustics: Some(CausticOptions { photons: 8192, radius_mm: 2.0, max_depth: 8, seed: 81 }),
+ ..Default::default()
+ };
+ let mut image = request(1);
+ image.camera.fov = 0.000001;
+ let mut mapped =
+ Task::new(executor.context.clone(), rough_glass_fixture(thin, 0.45, Vec3::ZERO, 0.0), image, mapped_options, CancelToken::default())
+ .unwrap();
+ mapped.options.max_depth = 1;
+ for _ in 0..mapped_options.samples {
+ mapped.complete_sample().unwrap();
+ }
+ let mapped_one = mapped.read_linear().unwrap()[0];
+ assert!(mapped.photons.as_ref().unwrap().ready());
+ mapped.sample = 0;
+ mapped.lane = 0;
+ mapped.offset = 0;
+ mapped.options.max_depth = 2;
+ for _ in 0..mapped_options.samples {
+ mapped.complete_sample().unwrap();
+ }
+ let mapped_two = mapped.read_linear().unwrap()[0];
+ assert!(
+ mapped_one[0] > 0.0 && mapped_one[0].is_finite(),
+ "primary rough gather must retain transmitted caustics: thin={thin}, {mapped_one:?}"
+ );
+ assert_eq!(mapped_one, mapped_two, "a sampled continuous prefix cannot add the same photon-estimated suffix twice: thin={thin}");
+ let maximum_depth = render(false, 16);
+ assert!(
+ maximum_depth[..3].iter().all(|value| value.is_finite() && *value > 0.0),
+ "all admitted sheet/interface events fit the fixed request cap: {maximum_depth:?}"
+ );
+ for pixel in [two, mapped_one, mapped_two, maximum_depth] {
+ for channel in 1..3 {
+ assert!(
+ (pixel[channel] - pixel[0]).abs() <= pixel[0].abs() * 1e-5 + 1e-7,
+ "non-spectral white caustics must remain achromatic: {pixel:?}"
+ );
+ }
+ }
+ }
+ let volume = |map: bool| {
+ let options = JobOptions {
+ samples: 64,
+ max_depth: 1,
+ nested_media: true,
+ lighting: Some(lighting),
+ caustics: map.then_some(CausticOptions { photons: 8192, radius_mm: 0.6, max_depth: 8, seed: 81 }),
+ ..Default::default()
+ };
+ let mut image = request(1);
+ image.camera.distance = 0.01;
+ image.camera.fov = 0.000001;
+ let mut task =
+ Task::new(executor.context.clone(), rough_glass_fixture(false, 0.0, Vec3::ZERO, 2.0), image, options, CancelToken::default()).unwrap();
+ for _ in 0..options.samples {
+ task.complete_sample().unwrap();
+ }
+ task.read_linear().unwrap()[0]
+ };
+ assert_eq!(volume(false), [0.0, 0.0, 0.0, 1.0], "the hard source lies beyond a genuinely refracting closed boundary");
+ let mapped = volume(true);
+ assert!(
+ mapped[0] > 0.0 && mapped[..3].iter().all(|value| value.is_finite()),
+ "primary selected-HG must gather refracted volume caustics: {mapped:?}"
+ );
+}
+
+#[test]
+fn rough_volume_photon_kernels_and_hg_delta_connection_match_independent_measures() {
+ use solidcraft_render::job::{CausticOptions, PunctualLightOptions, PunctualLights, StudioLighting};
+ let Some(executor) = executor() else { return };
+ let context = &executor.context;
+ if context.device.limits().max_storage_buffers_per_shader_stage < 7 {
+ return;
+ }
+ let scene = rough_glass_fixture(false, 0.5, Vec3::new(0.2, 0.4, 0.8), 0.6);
+ let options = JobOptions {
+ max_depth: 16,
+ lighting: Some(StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.0, 0.0, 0.25],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ }),
+ caustics: Some(CausticOptions { photons: 4, radius_mm: 1.0, ..Default::default() }),
+ ..Default::default()
+ };
+ let mut task = Task::new(context.clone(), scene, request(5), options, CancelToken::default()).unwrap();
+ assert_eq!(task.photons.as_ref().unwrap().progress().done, 0, "selected optical pipeline warm-up cannot advance photon work");
+ task.sample = 1;
+ assert!(task.read_linear().unwrap().iter().all(|pixel| *pixel == [0.0; 4]), "actual-binding optical warm-up must leave film untouched");
+ task.sample = 0;
+ let resources = task.photons.as_ref().unwrap();
+ let source = format!(
+ "{}\n@compute @workgroup_size(1) fn optical_density_reference() {{
+ if u.sampling.z==0u {{return;}}
+ let hit=trace_precise(vec3<f32>(0.1,0.0,2.0),vec3<f32>(0.0),vec3<f32>(0.0,0.0,-1.0),false,0xffffffffu,0.0,false);
+ var t=triangle(hit.triangle);t.glass=vec4<f32>(0.5,0.0,0.0,0.0);
+ let medium=Medium(t.optics.w,1.5,vec3<f32>(0.2,0.4,0.8),vec2<f32>(0.6,0.3));
+ accumulation[0]=vec4<f32>(photon_gather_glass(t,vec3<f32>(0.0,0.0,0.5),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,-1.0),1.0,1.5,0.0,0),1.0);
+ accumulation[1]=vec4<f32>(photon_gather_volume(vec3<f32>(0.0),vec3<f32>(0.0,0.0,-1.0),medium),1.0);
+ var sum=vec3<f32>(0.0);
+ for(var trial=0u;trial<4096u;trial+=1u) {{
+ var reservoir:PhotonReservoir;reservoir.rng=trial^0x5b3d17u;
+ photon_offer(&reservoir,PrecisePoint(vec3<f32>(0.0),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,1.0),vec3<f32>(1.0,0.0,0.0),vec3<f32>(0.0),0u,1u,0);
+ photon_offer(&reservoir,PrecisePoint(vec3<f32>(0.0),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,1.0,0.0),vec3<f32>(0.0),0u,2u,0);
+ photon_offer(&reservoir,PrecisePoint(vec3<f32>(0.0),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0),0u,3u,0);
+ sum+=reservoir.flux*f32(reservoir.visits);
+ }}
+ accumulation[3]=vec4<f32>(sum/4096.0,1.0);
+ var narrow=t;narrow.glass.x=0.001;
+ accumulation[4]=vec4<f32>(glass_evaluate_cosine(narrow.glass,vec3<f32>(0.0,0.0,-1.0),unit(vec3<f32>(0.0002,0.0,1.0)),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),1.0,1.5,0.0),1.0);
+ for(var case_index=0u;case_index<18u;case_index+=1u) {{
+ let vertices=max(1u,case_index-min(case_index,1u));
+ let trials=select(4096u,1u,case_index<3u);var total=vec3<f32>(0.0);
+ for(var trial=0u;trial<trials;trial+=1u) {{
+ var pending:array<vec4<u32>,6>;var pending_count=0u;var pending_rng=trial^(vertices*0x45d9f3bu)^0x6ef372d1u;
+ if case_index==0u {{glass_offer_light(&pending,&pending_count,&pending_rng,PrecisePoint(vec3<f32>(0.0),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,-1.0),vec3<f32>(1.0),1.5,1.5,0xffffffffu,1u,medium);}}
+ else {{
+ for(var vertex=0u;vertex<vertices;vertex+=1u) {{
+ let value=f32(vertex+1u);var prefix=vec3<f32>(value,value*value,select(0.0,1.0,(vertex&1u)==0u));
+ if case_index==1u {{prefix=vec3<f32>(1.0);}}
+ glass_offer_light(&pending,&pending_count,&pending_rng,PrecisePoint(vec3<f32>(0.0,0.0,0.5),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,-1.0),prefix,1.0,1.5,hit.triangle,0u,glass_vacuum());
+ }}
+ }}
+ total+=glass_resolve_light(&pending,pending_count,0.0);
+ }}
+ var output_index=select(2u,5u,case_index==1u);if case_index>=2u {{output_index=case_index+4u;}}
+ accumulation[output_index]=vec4<f32>(total/f32(trials),1.0);
+ }}
+ }}
+ @compute @workgroup_size(1) fn optical_event_limit_reference() {{
+ if u.sampling.z==0u {{return;}}
+ var pending:array<vec4<u32>,6>;var pending_count=u.sampling.y;var pending_rng=0u;
+ glass_offer_light(&pending,&pending_count,&pending_rng,PrecisePoint(vec3<f32>(0.0),vec3<f32>(0.0)),vec3<f32>(0.0,0.0,-1.0),vec3<f32>(1.0),1.0,1.5,0u,0u,glass_vacuum());
+ }}
+ @compute @workgroup_size(1) fn optical_precision_reference() {{
+ if u.sampling.z==0u {{return;}}
+ var response=vec3<f32>(0.0);
+ if u.image.z==0u {{
+ response=glass_evaluate_cosine(vec4<f32>(1e-9,0.0,0.0,0.0),vec3<f32>(0.0,0.0,-1.0),vec3<f32>(0.0,0.0,-1.0),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),1.0,bitcast<f32>(0x3f800001u),0.0);
+ }} else {{response=vec3<f32>(glass_response_product(1e30,1e30));}}
+ accumulation[0]=vec4<f32>(response,1.0);
+ }}",
+ photons::shader_source().unwrap()
+ );
+ let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&resources.layout)],
+ immediate_size: 0,
+ });
+ let constants = [("GLASS_DELTA_LIGHTS", 1.0)];
+ let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("optical_density_reference"),
+ compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },
+ cache: None,
+ });
+ warm_up(&context.device, &context.queue, &pipeline, &task.bind, &context.healthy).unwrap();
+ // Every triangle belongs to the same closed body. Use triangle0 only as a
+ // body identifier; the receiver's actual outward normal is explicitly +Z.
+ let heads = 8_usize;
+ let mut words = vec![0_u32; 16 + heads + 4 * 16];
+ words[0] = 4;
+ words[1] = heads as u32;
+ words[2] = 1.0_f32.to_bits();
+ words[6..9].fill((-10.0_f32).to_bits());
+ words[16..16 + heads].fill(u32::MAX);
+ let pi = std::f32::consts::PI;
+ for (index, (position, incoming, flux, kind, receiver, side)) in [
+ ([0.0_f32, 0.0, 0.59], [0.0, 0.0, 1.0], [pi, 2.0 * pi, 3.0 * pi], 2, 0, 0),
+ ([0.0, 0.0, -0.1], [0.0, 0.0, -1.0], [pi, 2.0 * pi, 3.0 * pi], 3, 1.0_f32.to_bits(), 0),
+ ([0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [1e6; 3], 3, 2.0_f32.to_bits(), 0),
+ ([0.0, 0.0, 0.5], [0.0, 0.0, 1.0], [1e6; 3], 2, 0, 1),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let cell = position.map(|value| (value + 10.0).floor() as u32);
+ let hash = (cell[0].wrapping_mul(73856093) ^ cell[1].wrapping_mul(19349663) ^ cell[2].wrapping_mul(83492791)) as usize & (heads - 1);
+ let record = 16 + heads + index * 16;
+ for (at, vector) in [(0, position), (4, incoming), (8, flux), (12, [0.0, 0.0, 1.0])] {
+ for (axis, value) in vector.into_iter().enumerate() {
+ words[record + at + axis] = value.to_bits();
+ }
+ }
+ words[record + 3] = words[16 + hash];
+ words[16 + hash] = index as u32;
+ words[record + 7] = receiver;
+ words[record + 11] = kind;
+ words[record + 15] = side | 4; // Punctual source0, plus the virtual-side bits.
+ }
+ let bytes: Vec<_> = words.into_iter().flat_map(u32::to_le_bytes).collect();
+ context.queue.write_buffer(&resources.buffer, 0, &bytes);
+ context.queue.write_buffer(&task.uniform, 0, &task.parameters(1).unwrap());
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ let actual = task.read_linear().unwrap();
+ let reflection = 0.04 / (4.0 * std::f64::consts::PI * 0.5_f64.powi(4));
+ let transmitted = 0.96 / (0.25 * std::f64::consts::PI * 0.5_f64.powi(4));
+ let phase = |cosine: f64| 0.91 / (4.0 * std::f64::consts::PI * (1.09 - 0.6 * cosine).powf(1.5));
+ let outgoing = Vec3::new(0.0002, 0.0, 1.0).normalized().unwrap();
+ let narrow = solidcraft_render::glass_model::GlassModel { roughness: 0.001, ..Default::default() }
+ .evaluate(-Vec3::Z, outgoing, Vec3::Z, 1.0, 1.5, 550.0)
+ .unwrap()
+ .value
+ * outgoing.z;
+ for (channel, absorption) in [0.2, 0.4, 0.8].into_iter().enumerate() {
+ let scalar = (channel + 1) as f64;
+ for (pixel, expected) in
+ [reflection * scalar, phase(1.0) * 1.25 * scalar, phase(-1.0) * 16.0 * (-0.25_f64 * (absorption + 0.6)).exp()].into_iter().enumerate()
+ {
+ assert!(
+ (f64::from(actual[pixel][channel]) - expected).abs() < expected * 0.0002,
+ "kernel{pixel}/channel{channel}: {actual:?} != {expected}"
+ );
+ }
+ assert!((actual[3][channel] - 1.0).abs() < 0.06, "one-record reservoir must preserve every eligible visit in expectation: {actual:?}");
+ assert!(
+ (f64::from(actual[4][channel]) - narrow).abs() < narrow * 0.0003,
+ "representable facet sine must survive an f32 rounded-one cosine: {actual:?} != {narrow}"
+ );
+ let seam = transmitted * 16.0 * (-0.25_f64 * (absorption + 0.6)).exp();
+ assert!(
+ (f64::from(actual[5][channel]) - seam).abs() < seam * 0.0003,
+ "an exact coplanar sibling at the producing seam cannot block the connection: {actual:?} != {seam}"
+ );
+ }
+ for vertices in 1_usize..=16 {
+ let count = vertices as f64;
+ let sum = [count * (count + 1.0) / 2.0, count * (count + 1.0) * (2.0 * count + 1.0) / 6.0, vertices.div_ceil(2) as f64];
+ let observed = actual[5 + vertices];
+ for (channel, total) in sum.into_iter().enumerate() {
+ let expected = f64::from(actual[5][channel]) * total;
+ assert!(
+ (f64::from(observed[channel]) - expected).abs() < expected * 0.06,
+ "one camera light request must estimate the complete K={vertices} colored vertex sum: {observed:?} vs {expected}"
+ );
+ }
+ }
+ assert_eq!(actual[6], actual[5], "K=1 retains the exact deterministic direct contribution");
+ // A finite-radius packet outside a source's omission sphere must not leak
+ // into a receiver inside that sphere. Source metadata remains one packed word.
+ let minimum_offset = PARAMETER_BYTES - PUNCTUAL_PARAMETER_BYTES as usize - 16 + 28;
+ context.queue.write_buffer(&task.uniform, minimum_offset as u64, &0.3_f32.to_le_bytes());
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ let omitted = task.read_linear().unwrap();
+ assert!(omitted[..3].iter().all(|pixel| *pixel == [0.0, 0.0, 0.0, 1.0]), "receiver-side point-source minimum is physical: {omitted:?}");
+ let overflow = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("optical_event_limit_reference"),
+ compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },
+ cache: None,
+ });
+ context.queue.write_buffer(&task.uniform, 0, &[0; PARAMETER_BYTES]);
+ warm_up(&context.device, &context.queue, &overflow, &task.bind, &context.healthy).unwrap();
+ context.queue.write_buffer(&task.uniform, 0, &task.parameters(1).unwrap());
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&overflow);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ let failure = task.read_linear().unwrap_err();
+ assert_eq!(failure.code, ErrorCode::InvalidScene);
+ assert!(failure.message.contains("light-event"));
+ let precision = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("optical_precision_reference"),
+ compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() },
+ cache: None,
+ });
+ context.queue.write_buffer(&task.uniform, 0, &[0; PARAMETER_BYTES]);
+ warm_up(&context.device, &context.queue, &precision, &task.bind, &context.healthy).unwrap();
+ for case in 0_u32..2 {
+ context.queue.write_buffer(&task.failures, 0, &[0; FAILURE_BYTES as usize]);
+ let mut parameters = task.parameters(1).unwrap();
+ parameters[8..12].copy_from_slice(&case.to_le_bytes());
+ context.queue.write_buffer(&task.uniform, 0, &parameters);
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&precision);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ let failure = task.read_linear().unwrap_err();
+ assert_eq!(failure.code, ErrorCode::InvalidScene);
+ assert!(
+ failure.message.contains("optical response"),
+ "near-matched narrow BTDF and response times valid source must refuse arithmetic overflow, case{case}: {failure}"
+ );
+ }
+}
+
+#[test]
+fn photon_density_kernel_counts_hash_collisions_once_and_respects_receiver_support() {
+ let Some(executor) = executor() else { return };
+ let context = &executor.context;
+ if context.device.limits().max_storage_buffers_per_shader_stage < 7 {
+ return;
+ }
+ let mut scene = glass_slab(true);
+ let material = OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 0.5, 1.0).unwrap();
+ scene.meshes[0].transmission = None;
+ scene.meshes[0].surface = Some(material);
+ let mut other = scene.meshes[0].clone();
+ other.name = "other density receiver".into();
+ for p in &mut Arc::make_mut(&mut other.mesh).positions {
+ p.z += 0.02;
+ }
+ scene.meshes.push(other);
+ scene.bounds = scene.bounds.union(&scene.meshes[1].mesh.bounds());
+ let upload = scene::flatten(&scene, Vec3::ZERO, &CancelToken::default()).unwrap();
+ let word = |index: usize| u32::from_le_bytes(upload.geometry[index * 4..index * 4 + 4].try_into().unwrap());
+ let material_base = (word(2) & scene::MATERIAL_OFFSET_MASK) as usize;
+ let receiver = |body: f32| {
+ (0..word(0) as usize).find(|i| f32::from_bits(word(material_base + word(4 + i * 4 + 3) as usize * 20 + 11)) == body).unwrap() as u32
+ };
+ let first = receiver(1.0);
+ let second = receiver(2.0);
+ let options = JobOptions {
+ caustics: Some(solidcraft_render::job::CausticOptions { photons: 4, radius_mm: 1.0, ..Default::default() }),
+ ..Default::default()
+ };
+ let mut task = Task::new(context.clone(), scene, request(2), options, CancelToken::default()).unwrap();
+ assert_eq!(task.photons.as_ref().unwrap().progress().done, 0, "setup warm-up cannot consume admitted photon work");
+ task.sample = 1;
+ assert!(task.read_linear().unwrap().iter().all(|pixel| *pixel == [0.0; 4]), "actual-binding zero-work warm-up cannot write camera film");
+ task.sample = 0;
+ let resources = task.photons.as_ref().unwrap();
+ let cancelled = CancelToken::default();
+ cancelled.cancel();
+ assert_eq!(resources.warm_up_actual(context, &task.uniform, &task.bind, &cancelled).unwrap_err().code, ErrorCode::Cancelled);
+ let source = format!(
+ "{}\n@compute @workgroup_size(1) fn density_reference() {{
+ let t=triangle(u32(u.eye.w));
+ accumulation[0]=vec4<f32>(photon_gather(t,u.eye.xyz,vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0)),1.0);
+ }}",
+ photons::shader_source().unwrap()
+ );
+ let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&resources.layout)],
+ immediate_size: 0,
+ });
+ let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("density_reference"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let heads = 8_usize;
+ let mut words = vec![0_u32; 16 + heads + 4 * 16];
+ words[0] = 4;
+ words[1] = heads as u32;
+ words[2] = 1.0_f32.to_bits();
+ words[6] = (-10.0_f32).to_bits();
+ words[7] = (-10.0_f32).to_bits();
+ words[8] = 0.5_f32.to_bits();
+ words[16..16 + heads].fill(u32::MAX);
+ let pi = std::f32::consts::PI;
+ let fixtures = [
+ ([0.0_f32, 0.0, 0.5], [pi, 2.0 * pi, 3.0 * pi], [0.0, 0.0, 1.0], first),
+ ([0.1, 0.0, 0.52], [1000.0; 3], [0.0, 0.0, 1.0], second), // Different body.
+ ([0.1, 0.1, 0.7], [1000.0; 3], [0.0, 0.0, 1.0], first), // Outside plane band.
+ ([0.2, 0.0, 0.5], [1000.0; 3], [0.0, 0.0, -1.0], first), // Opposite normal.
+ ];
+ for (index, (point, flux, normal, body)) in fixtures.into_iter().enumerate() {
+ let cell = [((point[0] + 10.0).floor()) as i32, ((point[1] + 10.0).floor()) as i32, (point[2] - 0.5).floor() as i32];
+ let hash = ((cell[0] as u32).wrapping_mul(73856093) ^ (cell[1] as u32).wrapping_mul(19349663) ^ (cell[2] as u32).wrapping_mul(83492791))
+ as usize
+ & (heads - 1);
+ let record = 16 + heads + index * 16;
+ for (at, vector) in [(0, point), (4, [0.0, 0.0, 1.0]), (8, flux), (12, normal)] {
+ for (axis, value) in vector.into_iter().enumerate() {
+ words[record + at + axis] = value.to_bits();
+ }
+ }
+ words[record + 3] = words[16 + hash];
+ words[16 + hash] = index as u32;
+ words[record + 7] = body;
+ words[record + 11] = 1;
+ }
+ let bytes: Vec<_> = words.into_iter().flat_map(u32::to_le_bytes).collect();
+ context.queue.write_buffer(&resources.buffer, 0, &bytes);
+ let mut params = vec![0; 32];
+ scene::vector(&mut params, Vec3::new(0.0, 0.0, 0.5), first as f32);
+ params.resize(PARAMETER_BYTES, 0);
+ context.queue.write_buffer(&task.uniform, 0, &params);
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ let actual = task.read_linear().unwrap()[0];
+ // The one eligible packet has flux [pi,2pi,3pi], Lambert f=1/pi,
+ // and the disk kernel is1/pi. Hash collisions must not multiply it.
+ for (actual, expected) in actual.into_iter().zip([1.0 / pi, 2.0 / pi, 3.0 / pi, 1.0]) {
+ assert!((actual - expected).abs() < 2e-5, "density kernel {actual} != {expected}");
+ }
+}
+
+fn photon_receiver_fixture(scattering: f64) -> ProductScene {
+ let mut source = glass_slab(false);
+ source.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.0).unwrap());
+ let optics = clear_glass();
+ source.meshes[0].transmission = Some(if scattering > 0.0 {
+ optics.with_subsurface(solidcraft_render::transmission::subsurface::Subsurface { scattering_per_mm: scattering, anisotropy: 0.0 }).unwrap()
+ } else {
+ optics
+ });
+ let floor = Mesh {
+ positions: vec![Vec3::new(-8.0, -8.0, -1.0), Vec3::new(8.0, -8.0, -1.0), Vec3::new(8.0, 8.0, -1.0), Vec3::new(-8.0, 8.0, -1.0)],
+ normals: vec![Vec3::Z; 4],
+ triangles: vec![[0, 1, 2], [0, 2, 3]],
+ tri_face: vec![0, 0],
+ ..Default::default()
+ };
+ source.bounds = source.bounds.union(&floor.bounds());
+ source.meshes.push(ProductMesh {
+ name: "photon Lambert receiver".into(),
+ mesh: Arc::new(floor),
+ color: [255; 3],
+ opacity: 1.0,
+ surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 0.5, 1.0).unwrap()),
+ transmission: None,
+ faces: Vec::new(),
+ });
+ source
+}
+
+fn photon_map_probe(task: &mut Task, position: Vec3) -> [f32; 4] {
+ let maximum = task.photons.as_ref().unwrap().maximum_quanta();
+ for _ in 0..maximum {
+ if task.photons.as_ref().unwrap().ready() {
+ break;
+ }
+ task.dispatch().unwrap();
+ }
+ assert!(task.photons.as_ref().unwrap().ready(), "bounded photon prepass must finish");
+ let context = &task.context;
+ let resources = task.photons.as_ref().unwrap();
+ let source=format!("{}\n@compute @workgroup_size(1) fn photon_map_reference() {{
+ var receiver=triangle(0u);for(var i=0u;i<geometry[0];i+=1u) {{let candidate=triangle(i);if candidate.optics.w==2.0 {{receiver=candidate;break;}}}}
+ accumulation[0]=vec4<f32>(photon_gather(receiver,u.eye.xyz,vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0),vec3<f32>(0.0,0.0,1.0)),1.0);
+ }}",photons::shader_source().unwrap());
+ let shader = context.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(source.into()) });
+ let layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&resources.layout)],
+ immediate_size: 0,
+ });
+ let pipeline = context.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None,
+ layout: Some(&layout),
+ module: &shader,
+ entry_point: Some("photon_map_reference"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ // Receiver-side source-minimum clipping needs the actual authored sources,
+ // even though this numerical entry replaces only the probe's eye position.
+ let mut params = task.parameters(1).unwrap();
+ let mut eye = Vec::new();
+ scene::vector(&mut eye, position, 0.0);
+ params[32..48].copy_from_slice(&eye);
+ context.queue.write_buffer(&task.uniform, 0, &params);
+ let mut encoder = context.device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &task.bind, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ context.queue.submit([encoder.finish()]);
+ task.sample = 1;
+ task.read_linear().unwrap()[0]
+}
+
+#[test]
+fn delta_source_photon_power_matches_directional_and_point_disk_integrals() {
+ use solidcraft_render::job::{
+ CausticOptions, DirectionalLightOptions, DirectionalLights, PunctualLightOptions, PunctualLights, SpotConeOptions, StudioLighting,
+ };
+ let Some(executor) = executor() else { return };
+ if executor.context.device.limits().max_storage_buffers_per_shader_stage < 7 {
+ return;
+ }
+ let point = PunctualLightOptions {
+ position_mm: [0.0, 0.0, 4.0],
+ color: [1.0; 3],
+ intensity: 25.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ };
+ let directional = StudioLighting {
+ sun: None,
+ environment: [0.0; 3],
+ directional_lights: DirectionalLights::new(&[DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }])
+ .unwrap(),
+ ..Default::default()
+ };
+ let spot = PunctualLightOptions {
+ cone: Some(SpotConeOptions {
+ emitted_axis: [0.0, 0.0, -1.0],
+ inner_half_angle_radians: 40_f64.to_radians(),
+ outer_half_angle_radians: 60_f64.to_radians(),
+ }),
+ ..point
+ };
+ let radius = 3.0_f64;
+ let point_integral = 2.0 * 25.0 / (radius * radius) * (1.0 - 5.0 / (25.0 + radius * radius).sqrt()) / std::f64::consts::PI;
+ for (lighting, expected) in [
+ (directional, 1.0 / std::f64::consts::PI),
+ (
+ StudioLighting { sun: None, environment: [0.0; 3], punctual_lights: PunctualLights::new(&[point]).unwrap(), ..Default::default() },
+ point_integral,
+ ),
+ (
+ StudioLighting { sun: None, environment: [0.0; 3], punctual_lights: PunctualLights::new(&[spot]).unwrap(), ..Default::default() },
+ point_integral,
+ ),
+ ] {
+ let options = JobOptions {
+ lighting: Some(lighting),
+ caustics: Some(CausticOptions { photons: 16384, radius_mm: radius, max_depth: 4, seed: 81 }),
+ ..Default::default()
+ };
+ let mut task = Task::new(executor.context.clone(), photon_receiver_fixture(0.0), request(1), options, CancelToken::default()).unwrap();
+ let actual = photon_map_probe(&mut task, Vec3::new(0.0, 0.0, -1.0));
+ for value in actual.into_iter().take(3) {
+ assert!((f64::from(value) - expected).abs() < expected * 0.12, "delta source photon power {actual:?} != disk integral {expected}");
+ }
+ }
+}
+
+#[test]
+fn photon_subsurface_flight_precedes_a_closer_analytic_emitter() {
+ use solidcraft_render::job::{AreaLight, AreaLights, CausticOptions, PunctualLightOptions, PunctualLights, SpotConeOptions, StudioLighting};
+ let Some(executor) = executor() else { return };
+ if executor.context.device.limits().max_storage_buffers_per_shader_stage < 7 {
+ return;
+ }
+ let lighting = StudioLighting {
+ sun: None,
+ environment: [0.0; 3],
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.0, 0.0, 2.0],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: Some(SpotConeOptions {
+ emitted_axis: [0.0, 0.0, -1.0],
+ inner_half_angle_radians: 3_f64.to_radians(),
+ outer_half_angle_radians: 6_f64.to_radians(),
+ }),
+ }])
+ .unwrap(),
+ area_lights: AreaLights::new(&[AreaLight { center: [0.0; 3], u: [0.25, 0.0, 0.0], v: [0.0, 0.25, 0.0], radiance: [0.0; 3] }]).unwrap(),
+ ..Default::default()
+ };
+ let options = JobOptions {
+ lighting: Some(lighting),
+ caustics: Some(CausticOptions { photons: 16384, radius_mm: 0.3, max_depth: 16, seed: 81 }),
+ ..Default::default()
+ };
+ let probe = |scattering| {
+ let mut task = Task::new(executor.context.clone(), photon_receiver_fixture(scattering), request(1), options, CancelToken::default()).unwrap();
+ photon_map_probe(&mut task, Vec3::new(1.0, 0.0, -1.0))
+ };
+ assert_eq!(probe(0.0), [0.0, 0.0, 0.0, 1.0], "every unscattered narrow-cone photon meets the analytic blocker");
+ let scattered = probe(2.0);
+ assert!(
+ scattered[0] > 1e-5 && scattered.iter().all(|v| v.is_finite()),
+ "a free flight before that blocker must retain the off-axis scattering path: {scattered:?}"
+ );
+}
+
+#[test]
+fn contained_punctual_connections_apply_physical_beer_and_hg_survival_without_an_ior_jump() {
+ use solidcraft_render::job::{PunctualLightOptions, PunctualLights, StudioLighting};
+ let Some(executor) = executor() else { return };
+ let sigma = Vec3::new(0.2, 0.4, 0.0);
+ for scattering in [0.0, 0.4] {
+ let mut source = photon_receiver_fixture(scattering);
+ source.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap());
+ let mut optics = solidcraft_render::transmission::Transmission::new(sigma, None).unwrap();
+ if scattering > 0.0 {
+ optics = optics
+ .with_subsurface(solidcraft_render::transmission::subsurface::Subsurface { scattering_per_mm: scattering, anisotropy: 0.0 })
+ .unwrap();
+ }
+ source.meshes[0].transmission = Some(optics);
+ for p in &mut Arc::make_mut(&mut source.meshes[1].mesh).positions {
+ p.z = -0.25;
+ }
+ source.bounds = source.meshes[0].mesh.bounds();
+ let lighting = StudioLighting {
+ sun: None,
+ environment: [0.0; 3],
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.5, 0.0, 0.0],
+ color: [1.0; 3],
+ intensity: 0.0625,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ };
+ let samples = if scattering > 0.0 { 2048 } else { 1 };
+ let options = JobOptions { nested_media: true, samples, max_depth: 1, lighting: Some(lighting), ..Default::default() };
+ let mut image = request(1);
+ image.camera.target = Vec3::new(0.0, 0.0, -0.25);
+ image.camera.distance = 0.5;
+ image.camera.fov = 0.00001;
+ let mut task = Task::new(executor.context.clone(), source, image, options, CancelToken::default()).unwrap();
+ while task.sample < samples {
+ task.complete_sample().unwrap();
+ }
+ let actual = task.read_linear().unwrap()[0];
+ // The source is0.5mm off the eye→receiver segment, avoiding an ideal
+ // point singularity on the camera ray. All endpoints remain inside IOR1.5
+ // and no eta conversion applies. An HG collision now has hard-source NEE
+ // at maxdepth1, so include its independent one-dimensional expectation.
+ // The zero-collision atom has mass exp(-sigma_s*0.5); collision distance
+ // has density sigma_s*exp(-sigma_s*s), for0<s<0.5. Integrate both first
+ // and second moments to set the Monte Carlo tolerance from real variance.
+ for (value, absorption) in actual.into_iter().take(3).zip([sigma.x, sigma.y, sigma.z]) {
+ let receiver_distance = (0.5_f64.powi(2) + 0.25_f64.powi(2)).sqrt();
+ let endpoint = 0.0625 * 0.25 / (std::f64::consts::PI * receiver_distance.powi(3))
+ * (-absorption * 0.5 - (absorption + scattering) * receiver_distance).exp();
+ let mass = (-scattering * 0.5).exp();
+ let mut first = mass * endpoint;
+ let mut second = mass * endpoint * endpoint;
+ let intervals = 1024_u32;
+ let step = 0.5 / f64::from(intervals);
+ for index in 0..=intervals {
+ let distance = f64::from(index) * step;
+ let light_distance = (0.5_f64.powi(2) + (0.25 - distance).powi(2)).sqrt();
+ let weight = 0.0625 / (4.0 * std::f64::consts::PI * light_distance.powi(2))
+ * (-absorption * distance - (absorption + scattering) * light_distance).exp();
+ let density = scattering * (-scattering * distance).exp();
+ let quadrature = if index == 0 || index == intervals {
+ 1.0
+ } else if index.is_multiple_of(2) {
+ 2.0
+ } else {
+ 4.0
+ };
+ first += step / 3.0 * quadrature * density * weight;
+ second += step / 3.0 * quadrature * density * weight * weight;
+ }
+ let standard_error = ((second - first * first).max(0.0) / f64::from(samples)).sqrt();
+ let tolerance = 6.0 * standard_error + 2e-5;
+ assert!(
+ (f64::from(value) - first).abs() < tolerance,
+ "contained Beer/HG={scattering}: {actual:?} != {first}, standard error{standard_error}"
+ );
+ }
+ }
+}
+
+#[test]
+fn gpu_embedded_receiver_keeps_the_legacy_straight_shadow_scale() {
+ use solidcraft_render::{
+ glass_model::GlassModel,
+ job::{PunctualLightOptions, PunctualLights, StudioLighting},
+ };
+ let Some(executor) = executor() else { return };
+ for (model, ior_scale) in [(None, 1.0), (Some(GlassModel::default()), 1.0), (Some(GlassModel { roughness: 0.35, ..Default::default() }), 2.25)] {
+ let mut source = photon_receiver_fixture(0.0);
+ source.meshes[0].surface = Some(OpaqueSurface::new(Vec3::ZERO, 0.0, 0.1, 1.5).unwrap());
+ let mut optics = solidcraft_render::transmission::Transmission::new(Vec3::ZERO, None).unwrap().with_shadow_transmission(true);
+ if let Some(model) = model {
+ optics = optics.with_model(model).unwrap();
+ }
+ source.meshes[0].transmission = Some(optics);
+ for p in &mut Arc::make_mut(&mut source.meshes[1].mesh).positions {
+ p.z = -0.25;
+ }
+ source.bounds = source.meshes[0].mesh.bounds();
+ let lighting = StudioLighting {
+ punctual_lights: PunctualLights::new(&[PunctualLightOptions {
+ position_mm: [0.0, 0.0, 0.75],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }])
+ .unwrap(),
+ ..Default::default()
+ };
+ let options = JobOptions { nested_media: true, samples: 1, max_depth: 1, lighting: Some(lighting), ..Default::default() };
+ let mut image = request(1);
+ image.camera.target = Vec3::new(0.0, 0.0, -0.25);
+ image.camera.distance = 0.5;
+ image.camera.fov = 0.00001;
+ let mut task = Task::new(executor.context.clone(), source, image, options, CancelToken::default()).unwrap();
+ task.complete_sample().unwrap();
+ let actual = task.read_linear().unwrap()[0];
+ assert_eq!(actual[3], 1.0);
+ // The inside eye sees a unit Lambert receiver. The point is 1 mm away
+ // along the normal, across one IOR-1.5 interface with power T = 0.96.
+ let expected = 0.96 * ior_scale / std::f64::consts::PI;
+ for value in &actual[..3] {
+ assert!((f64::from(*value) - expected).abs() < 2e-5, "model={model:?}: {actual:?} vs {expected}");
+ }
+ }
+}
+
#[test]
fn gpu_nonabsorbing_glass_sphere_white_furnace_conserves_radiance() {
let Some(executor) = executor() else { return };
@@ -546,6 +1942,9 @@ fn shader_validates_without_a_device() {
naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
assert_eq!(module.entry_points.iter().find(|entry| entry.name == "main").unwrap().workgroup_size, [PATH_WORKGROUP_SIZE, 1, 1]);
}
+ let source = photons::shader_source().unwrap();
+ let caustic = naga::front::wgsl::parse_str(&source).unwrap_or_else(|error| panic!("{}", error.emit_to_string(&source)));
+ naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&caustic).unwrap();
}
/// #6705: native compilers inline every call. With 33 inlined BVH walks in `main` (three path
@@ -2013,7 +3412,7 @@ fn opaque_scene_specialization_preserves_body_face_and_volume_media() {
assert_ne!(
scene_pipeline_variant(opaque, maps, false),
scene_pipeline_variant(opaque, maps, true),
- "single and nested medium stacks require distinct programs"
+ "disjoint and nested options retain separate scene cache entries"
);
}
}
@@ -2170,10 +3569,12 @@ fn path_device_limits_require_six_storage_buffers_without_changing_raster_defaul
let mut supported = wgpu::Limits::downlevel_defaults();
assert_eq!(supported.max_storage_buffers_per_shader_stage, 4);
assert!(device_limits(supported.clone()).is_err());
+ supported.max_storage_buffers_per_shader_stage = 6;
+ assert_eq!(device_limits(supported.clone()).unwrap().max_storage_buffers_per_shader_stage, 6);
supported.max_storage_buffers_per_shader_stage = 8;
let requested = device_limits(supported.clone()).unwrap();
let mut expected = wgpu::Limits::downlevel_defaults().using_resolution(supported);
- expected.max_storage_buffers_per_shader_stage = 6;
+ expected.max_storage_buffers_per_shader_stage = 7;
assert_eq!(requested, expected);
}
@@ -3555,11 +4956,20 @@ fn gpu_mapped_wood_preserves_index_matched_sheet_and_solid_transport() {
// exact identity. The mean map reflectance .5 receives three fixed lights.
let expected = 0.5 * (3.0 * 0.8 + 1.0 * 0.6 + 1.5 * 0.8) / std::f64::consts::PI;
for mapped in [false, true] {
- for thin in [true, false] {
+ for (thin, active_optics) in [(true, false), (false, false), (true, true)] {
+ if active_optics && !mapped {
+ continue;
+ }
let mut glass = glass_slab(thin).meshes.remove(0);
glass.name = "index matched glazing".into();
for position in &mut Arc::make_mut(&mut glass.mesh).positions {
position.z += 1.0;
+ if active_optics {
+ // A vertex anchor lies outside the board. The actual hit
+ // stays over it after the barycentric displacement is added.
+ position.x *= 4.0;
+ position.y *= 4.0;
+ }
}
glass.surface = Some(OpaqueSurface::new(Vec3::ZERO, 0., 1., 1.).unwrap());
glass.transmission =
@@ -3568,6 +4978,17 @@ fn gpu_mapped_wood_preserves_index_matched_sheet_and_solid_transport() {
if !mapped {
scene.meshes[0].surface = Some(OpaqueSurface::new(Vec3::new(0.5, 0.5, 0.5), 0., 1., 1.).unwrap());
}
+ if active_optics {
+ // A separate rough body selects the split optical producer
+ // without changing the index-matched sheet's identity oracle.
+ let mut rough = rough_glass_fixture(false, 0.35, Vec3::ZERO, 0.0).meshes.remove(0);
+ rough.name = "offscreen rough glazing".into();
+ for position in &mut Arc::make_mut(&mut rough.mesh).positions {
+ position.x += 100.0;
+ }
+ scene.bounds = scene.bounds.union(&rough.mesh.bounds());
+ scene.meshes.push(rough);
+ }
let mut image = request(16);
image.textures = mapped.then(|| resources.clone());
let mut task = Task::new(
@@ -3580,11 +5001,20 @@ fn gpu_mapped_wood_preserves_index_matched_sheet_and_solid_transport() {
.unwrap();
assert!(!task.opaque_scene);
assert_eq!(task.has_textures, mapped);
- task.complete_sample().unwrap_or_else(|error| panic!("thin={thin},mapped={mapped}: {error:?}"));
- for (pixel, value) in task.read_linear().unwrap_or_else(|error| panic!("thin={thin},mapped={mapped}: {error:?}")).iter().enumerate() {
- assert_eq!(value[3], 1.0, "thin={thin},mapped={mapped},pixel={pixel}");
+ assert_eq!(task.optical_resolve.is_some(), active_optics);
+ task.complete_sample().unwrap_or_else(|error| panic!("thin={thin}, mapped={mapped}, active optics={active_optics}: {error:?}"));
+ for (pixel, value) in task
+ .read_linear()
+ .unwrap_or_else(|error| panic!("thin={thin}, mapped={mapped}, active optics={active_optics}: {error:?}"))
+ .iter()
+ .enumerate()
+ {
+ assert_eq!(value[3], 1.0, "thin={thin}, mapped={mapped}, active optics={active_optics},pixel={pixel}");
for actual in value.iter().take(3) {
- assert!((f64::from(*actual) - expected).abs() < 2e-5, "thin={thin},mapped={mapped},pixel={pixel}: {value:?} vs {expected}");
+ assert!(
+ (f64::from(*actual) - expected).abs() < 2e-5,
+ "thin={thin}, mapped={mapped}, active optics={active_optics},pixel={pixel}: {value:?} vs {expected}"
+ );
}
}
}
diff --git a/crates/gpu/src/path/volume_tests.rs b/crates/gpu/src/path/volume_tests.rs
index 5090819a6e..5fa660a53d 100644
--- a/crates/gpu/src/path/volume_tests.rs
+++ b/crates/gpu/src/path/volume_tests.rs
@@ -680,10 +680,10 @@ fn volume_orthographic_segment(o: vec3<f32>, d: vec3<f32>, limit: f32) -> vec2<f
"#;
// The archived pre-GPU12 control fingerprint remains historical evidence:
// f373400816e40e803691ceb847d8c9d7983fd4744c3874a322363810c14b6d6c.
- // Upstream changed map filtering and producer specialization. Reconstruct
+ // Map filtering, optical transport and producer specialization can change. Reconstruct
// each current producer, changing only this signed primary hook/helper.
let old_pipeline = |opaque: bool| {
- let shader = if opaque { SHADER } else { SINGLE_MEDIUM_SHADER };
+ let shader = scene_shader(opaque);
assert_eq!(shader.matches(new_hook).count(), 1);
assert_eq!(shader.matches(helper).count(), 1);
let helper_block = format!("\n{helper}");
@@ -765,7 +765,7 @@ fn volume_orthographic_segment(o: vec3<f32>, d: vec3<f32>, limit: f32) -> vec2<f
_ => panic!("unexpected unchanged-volume fixture mode"),
}
// None and zero extinction use the opaque producer. The active fog
- // routes use the one-medium producer, with no maps or nested glass.
+ // routes use the general producer, with no maps or nested glass.
let opaque = mode < 2;
assert_eq!(use_opaque_pipeline(&source, options), opaque);
assert!(image.textures.is_none() && !options.nested_media);
diff --git a/crates/render/src/dielectric_oracle_tests.rs b/crates/render/src/dielectric_oracle_tests.rs
index 51c7c3add9..ab4e4566b4 100644
--- a/crates/render/src/dielectric_oracle_tests.rs
+++ b/crates/render/src/dielectric_oracle_tests.rs
@@ -76,3 +76,52 @@ fn hostile_optics_are_rejected_without_clamping() {
assert!(refract(Vec3::ZERO, Vec3::Z, 1.0, 1.5).is_err());
assert!(refract(Vec3::Z, Vec3::Z, 1.0, 1.5).is_err());
}
+
+#[test]
+fn zero_thickness_matched_sheet_transmits_at_exact_grazing() {
+ let sheet = Transmission::new(Vec3::new(100.0, 10.0, 1.0), Some(0.0)).unwrap();
+ for index in [1.0, 1.33, 1.5, 3.0] {
+ for cosine in [0.0, f64::EPSILON, 0.5, 1.0] {
+ let (reflected, transmitted) = slab(sheet, 0.0, cosine, index, index).unwrap();
+ assert_eq!(reflected, Vec3::ZERO);
+ assert_eq!(transmitted, Vec3::new(1.0, 1.0, 1.0));
+ }
+ // Positive physical thickness requires an actual crossing direction.
+ assert_eq!(slab(sheet, 1.0, 0.0, index, index), Err(TransmissionError::Angle));
+ }
+ // Zero thickness does not override total internal reflection.
+ let (reflected, transmitted) = slab(sheet, 0.0, 0.5, 1.5, 1.0).unwrap();
+ assert_eq!(reflected, Vec3::new(1.0, 1.0, 1.0));
+ assert_eq!(transmitted, Vec3::ZERO);
+}
+
+#[test]
+fn slab_energy_and_beer_order_hold_across_the_admitted_optical_domain() {
+ let clear = Transmission::new(Vec3::ZERO, None).unwrap();
+ let tinted = Transmission::new(Vec3::new(0.001, 0.1, 100.0), None).unwrap();
+ for outside in [1.0, 1.33, 1.5, 3.0] {
+ for inside in [1.0, 1.33, 1.5, 3.0] {
+ for cosine in [0.0, 1e-12, 0.01, 0.5, 0.9, 1.0] {
+ for thickness in [0.0, 1e-12, 1.0, 10000.0] {
+ if cosine == 0.0 && outside == inside && thickness > 0.0 {
+ continue;
+ }
+ let (r0, t0) = slab(clear, thickness, cosine, outside, inside).unwrap();
+ let (r, t) = slab(tinted, thickness, cosine, outside, inside).unwrap();
+ for (reflectance, transmittance, lossless_r, lossless_t) in
+ [(r.x, t.x, r0.x, t0.x), (r.y, t.y, r0.y, t0.y), (r.z, t.z, r0.z, t0.z)]
+ {
+ assert!(reflectance.is_finite() && transmittance.is_finite());
+ assert!((0.0..=1.0).contains(&reflectance));
+ assert!((0.0..=1.0).contains(&transmittance));
+ assert!((lossless_r + lossless_t - 1.0).abs() < 1e-12);
+ assert!(reflectance <= lossless_r + 1e-12);
+ assert!(transmittance <= lossless_t + 1e-12);
+ assert!(reflectance + transmittance <= 1.0 + 1e-12);
+ }
+ assert!(t.x >= t.y && t.y >= t.z);
+ }
+ }
+ }
+ }
+}
diff --git a/crates/render/src/glass_model.rs b/crates/render/src/glass_model.rs
new file mode 100644
index 0000000000..06f72dc48e
--- /dev/null
+++ b/crates/render/src/glass_model.rs
@@ -0,0 +1,899 @@
+//! Original bounded rough-dielectric, Cauchy dispersion and lossless thin-film math.
+//!
+//! The representative RGB wavelengths below define a three-band approximation,
+//! not a sampled spectrum or a colour-matching-function integration. Equations:
+//! Heitz (2018), https://jcgt.org/published/0007/04/01/paper.pdf (GGX VNDF);
+//! Walter et al. (2007), https://www.graphics.cornell.edu/~bjw/microfacetbsdf.pdf
+//! (refraction half-vector and Jacobian); Belcour and Barla (2017),
+//! https://hal.science/hal-01518344/document (Airy interference). No source code
+//! from those publications is incorporated here.
+//! Shading-normal measures follow Veach (1997), sections 5.3.3--5.3.4:
+//! https://graphics.stanford.edu/papers/veach_thesis/thesis.pdf.
+use crate::{surface::unit_direction, transmission};
+use serde::{Deserialize, Serialize};
+use solidcore_record::Vec3;
+use solidcraft_geom::Vec3Geom;
+use std::f64::consts::{PI, TAU};
+
+/// Fixed R, G, B representative bands. Thin films can alias in this approximation.
+pub const WAVELENGTHS_NM: [f64; 3] = [610.0, 550.0, 460.0];
+pub const MIN_WAVELENGTH_NM: f64 = 380.0;
+pub const MAX_WAVELENGTH_NM: f64 = 780.0;
+/// Fraunhofer wavelengths used for nd and vd; SCHOTT TIE-29, Table 1.
+pub const D_LINE_NM: f64 = 587.5618;
+pub const F_LINE_NM: f64 = 486.1327;
+pub const C_LINE_NM: f64 = 656.2725;
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Dispersion {
+ pub abbe_number: f64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ThinFilm {
+ pub ior: f64,
+ pub thickness_nm: f64,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct GlassModel {
+ pub roughness: f64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dispersion: Option<Dispersion>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub thin_film: Option<ThinFilm>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum GlassModelError {
+ Roughness,
+ Dispersion,
+ Film,
+ Ior,
+ Wavelength,
+ Angle,
+ Direction,
+ Sample,
+ Numerical,
+}
+impl std::fmt::Display for GlassModelError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Self::Roughness => "Glass roughness must be finite in [0, 1] with representable GGX width and peak",
+ Self::Dispersion => "Glass dispersion requires a finite Abbe number in [5, 200] and IOR in [1, 3] over 380..780 nm",
+ Self::Film => "Glass thin film requires finite IOR in [1, 3] and thickness in [0, 100000] nm",
+ Self::Ior => "Glass interface IOR must be finite in [1, 3]",
+ Self::Wavelength => "Glass wavelength must be finite in [380, 780] nm",
+ Self::Angle => "Glass incident cosine must be finite in [0, 1]",
+ Self::Direction => "Glass directions must be finite and nonzero; the normal must face the incident medium",
+ Self::Sample => "Glass sample coordinates must be finite in [0, 1)",
+ Self::Numerical => "Glass interface cannot be represented with finite nonnegative transport and density",
+ })
+ }
+}
+impl std::error::Error for GlassModelError {}
+pub type Result<T> = std::result::Result<T, GlassModelError>;
+
+/// One sampled radiance-transport continuation. `weight` is f*|cos(out)|/pdf,
+/// including Fresnel branch selection and the transmitted radiance IOR ratio.
+/// For delta events `pdf` is a discrete branch probability, not sr^-1. For the
+/// index-matched coated transmission singularity it is conditional on the sampled
+/// visible facet; delta paths must not use it as a continuous MIS density.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct InterfaceSample {
+ pub direction: Vec3,
+ pub weight: f64,
+ pub pdf: f64,
+ pub crosses: bool,
+ pub delta: bool,
+}
+
+/// Continuous interface value and matching full mixture density per solid angle.
+/// `evaluate` returns the BSDF; `evaluate_projected` includes outgoing projected
+/// cosine in `value`. Delta lobes return zero in this measure.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct InterfaceEvaluation {
+ pub value: f64,
+ pub pdf: f64,
+}
+
+fn valid_ior(ior: f64) -> bool {
+ ior.is_finite() && (1.0..=3.0).contains(&ior)
+}
+fn wavelength(value: f64) -> Result<()> {
+ if value.is_finite() && (MIN_WAVELENGTH_NM..=MAX_WAVELENGTH_NM).contains(&value) { Ok(()) } else { Err(GlassModelError::Wavelength) }
+}
+fn direction(value: Vec3) -> Result<Vec3> {
+ unit_direction(value).map_err(|_| GlassModelError::Direction)
+}
+
+// Compute positive products as a mantissa and a separate binary exponent. This
+// preserves finite ratios when numerator and denominator products would both
+// underflow, and refuses a genuinely unrepresentable positive result.
+fn positive_ratio(numerator: &[f64], denominator: &[f64]) -> Result<f64> {
+ let mut mantissa = 1.0;
+ let mut exponent = 0_i32;
+ for (values, divide) in [(numerator, false), (denominator, true)] {
+ for &value in values {
+ if !value.is_finite() || value <= 0.0 {
+ return Err(GlassModelError::Numerical);
+ }
+ let (scaled, adjustment) = if value < f64::MIN_POSITIVE { (value * 4503599627370496.0, -52) } else { (value, 0) };
+ let bits = scaled.to_bits();
+ let power = ((bits >> 52) & 0x7ff) as i32 - 1023 + adjustment;
+ let fraction = f64::from_bits((bits & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000);
+ if divide {
+ mantissa /= fraction;
+ exponent -= power;
+ } else {
+ mantissa *= fraction;
+ exponent += power;
+ }
+ while mantissa >= 2.0 {
+ mantissa *= 0.5;
+ exponent += 1;
+ }
+ while mantissa < 1.0 {
+ mantissa *= 2.0;
+ exponent -= 1;
+ }
+ }
+ }
+ let value = if exponent < -1022 {
+ (mantissa * 2.0_f64.powi(exponent + 1074)) * f64::from_bits(1)
+ } else if exponent <= 1023 {
+ mantissa * 2.0_f64.powi(exponent)
+ } else {
+ return Err(GlassModelError::Numerical);
+ };
+ if value.is_finite() && value > 0.0 { Ok(value) } else { Err(GlassModelError::Numerical) }
+}
+
+/// Adjoint shading-normal correction for a photon continuation. `incident`
+/// travels toward the interface, `outgoing` travels away; normals describe a
+/// fixed facet model. Remove the radiance transmission (ni/nt)^2 first. This is
+/// |wo.ns| |wi.ng| / (|wo.ng| |wi.ns|), with wo=-incident and wi=outgoing.
+/// Exact tangent projections have zero measure and return zero; invalid vectors
+/// and a nonrepresentable positive ratio are errors, never epsilon-clamped.
+pub fn importance_normal_correction(incident: Vec3, outgoing: Vec3, shading_normal: Vec3, geometric_normal: Vec3) -> Result<f64> {
+ let wo = -direction(incident)?;
+ let wi = direction(outgoing)?;
+ let ns = direction(shading_normal)?;
+ let ng = direction(geometric_normal)?;
+ let a = wo.dot(ns).abs();
+ let b = wi.dot(ng).abs();
+ let c = wo.dot(ng).abs();
+ let d = wi.dot(ns).abs();
+ if a == 0.0 || b == 0.0 || c == 0.0 || d == 0.0 {
+ return Ok(0.0);
+ }
+ positive_ratio(&[a, b], &[c, d])
+}
+
+/// Convert photon flux per geometric area to a shading-normal BSDF measure.
+/// `incoming_light` points from the receiver toward the photon's previous point.
+/// Multiply the surface density estimate by f * this ratio, without an extra
+/// cosine: the deposited flux already includes geometric projected incidence.
+pub fn surface_normal_measure(incoming_light: Vec3, shading_normal: Vec3, geometric_normal: Vec3) -> Result<f64> {
+ let incoming = direction(incoming_light)?;
+ let ns = direction(shading_normal)?;
+ let ng = direction(geometric_normal)?;
+ let numerator = incoming.dot(ns).abs();
+ let denominator = incoming.dot(ng).abs();
+ if numerator == 0.0 || denominator == 0.0 {
+ return Ok(0.0);
+ }
+ positive_ratio(&[numerator], &[denominator])
+}
+
+/// Uniform sphere kernel for a photon map gathered at an analog camera
+/// scattering collision: 3/(4*pi*r^3*sigma_s), in inverse mm^2. Light collision
+/// density is sigma_s times fluence; camera free-flight sampling already
+/// includes sigma_s, so it must be divided out here. Multiply by the phase
+/// function and photon flux. A ray-marched volume estimator has another measure.
+pub fn volume_photon_kernel(radius_mm: f64, sigma_s_per_mm: f64) -> Result<f64> {
+ if !radius_mm.is_finite() || radius_mm <= 0.0 || !sigma_s_per_mm.is_finite() || sigma_s_per_mm <= 0.0 {
+ return Err(GlassModelError::Numerical);
+ }
+ positive_ratio(&[3.0], &[4.0 * PI, radius_mm, radius_mm, radius_mm, sigma_s_per_mm])
+}
+
+impl GlassModel {
+ fn controls(self) -> Result<()> {
+ let alpha = self.roughness * self.roughness;
+ let peak_root = 1.0 / (alpha * PI.sqrt());
+ if !self.roughness.is_finite()
+ || !(0.0..=1.0).contains(&self.roughness)
+ || (self.roughness > 0.0 && (alpha == 0.0 || alpha * alpha == 0.0 || !(peak_root * peak_root).is_finite()))
+ {
+ return Err(GlassModelError::Roughness);
+ }
+ if self.dispersion.is_some_and(|d| !d.abbe_number.is_finite() || !(5.0..=200.0).contains(&d.abbe_number)) {
+ return Err(GlassModelError::Dispersion);
+ }
+ if self.thin_film.is_some_and(|f| !valid_ior(f.ior) || !f.thickness_nm.is_finite() || !(0.0..=100000.0).contains(&f.thickness_nm)) {
+ return Err(GlassModelError::Film);
+ }
+ Ok(())
+ }
+
+ pub fn validate(self, base_ior: f64) -> Result<()> {
+ self.controls()?;
+ if !valid_ior(base_ior) {
+ return Err(GlassModelError::Ior);
+ }
+ // Two-term normal Cauchy dispersion is monotone, so endpoints prove the
+ // complete bounded wavelength domain without silently clamping an IOR.
+ for nm in [MIN_WAVELENGTH_NM, MAX_WAVELENGTH_NM] {
+ if !valid_ior(self.cauchy(base_ior, nm)) {
+ return Err(GlassModelError::Dispersion);
+ }
+ }
+ Ok(())
+ }
+
+ pub fn spectral(self) -> bool {
+ self.dispersion.is_some() || self.thin_film.is_some_and(|film| film.thickness_nm > 0.0)
+ }
+
+ pub fn is_identity(self) -> bool {
+ self.roughness == 0.0 && self.dispersion.is_none() && self.thin_film.is_none_or(|film| film.thickness_nm == 0.0)
+ }
+
+ fn cauchy(self, base_ior: f64, nm: f64) -> f64 {
+ let Some(dispersion) = self.dispersion else { return base_ior };
+ let inverse_square = |nm: f64| 1.0 / (nm * nm);
+ let b = ((base_ior - 1.0) / dispersion.abbe_number) / (inverse_square(F_LINE_NM) - inverse_square(C_LINE_NM));
+ base_ior + b * (inverse_square(nm) - inverse_square(D_LINE_NM))
+ }
+
+ /// Two-term Cauchy approximation anchored at nd, with vd=(nd-1)/(nF-nC).
+ /// Abbe number alone is not a measured Sellmeier model for a named glass.
+ pub fn ior(self, base_ior: f64, wavelength_nm: f64) -> Result<f64> {
+ wavelength(wavelength_nm)?;
+ self.validate(base_ior)?;
+ Ok(self.cauchy(base_ior, wavelength_nm))
+ }
+
+ /// Lossless single-layer coherent Airy response. ni/nt are the actual IORs
+ /// at the supplied wavelength; dispersion is resolved by the caller. The
+ /// substrate's Snell cosine is preserved even when the film is evanescent.
+ pub fn fresnel(self, cosine: f64, ni: f64, nt: f64, wavelength_nm: f64) -> Result<transmission::Fresnel> {
+ self.controls()?;
+ wavelength(wavelength_nm)?;
+ if !cosine.is_finite() || !(0.0..=1.0).contains(&cosine) {
+ return Err(GlassModelError::Angle);
+ }
+ if !valid_ior(ni) || !valid_ior(nt) {
+ return Err(GlassModelError::Ior);
+ }
+ let bare = transmission::fresnel(cosine, ni, nt).map_err(|_| GlassModelError::Numerical)?;
+ let Some(film) = self.thin_film.filter(|film| film.thickness_nm > 0.0) else { return Ok(bare) };
+ if film.ior == ni || film.ior == nt || bare.transmitted_cosine.is_none() {
+ return Ok(bare);
+ }
+ if cosine == 0.0 {
+ return Ok(transmission::Fresnel { s: 1.0, p: 1.0, transmitted_cosine: bare.transmitted_cosine });
+ }
+ let transverse_square = ni * ni * (1.0 - cosine * cosine).max(0.0);
+ let film_longitudinal_square = film.ior * film.ior - transverse_square;
+ let qf = if film_longitudinal_square >= 0.0 {
+ Complex::real(film_longitudinal_square.sqrt())
+ } else {
+ Complex { re: 0.0, im: (-film_longitudinal_square).sqrt() }
+ };
+ let qi = ni * cosine;
+ let qt = nt * bare.transmitted_cosine.ok_or(GlassModelError::Numerical)?;
+ let k = TAU * film.thickness_nm / wavelength_nm;
+ let polarized = |p: bool| -> Result<f64> {
+ let (yi, yt, factor) = if p { (qi / (ni * ni), qt / (nt * nt), film.ior * film.ior) } else { (qi, qt, 1.0) };
+ let phase = qf.scale(k);
+ let amplitude = if phase.norm_square() < 1e-6 {
+ // Transfer matrix written with sin(delta)/qf. Its power series
+ // remains finite at the exact film critical angle qf=0, where
+ // the direct Airy quotient otherwise becomes 0/0.
+ let z2 = phase.mul(phase);
+ let z4 = z2.mul(z2);
+ let z6 = z4.mul(z2);
+ let a = Complex::real(1.0).sub(z2.scale(0.5)).add(z4.scale(1.0 / 24.0)).sub(z6.scale(1.0 / 720.0));
+ let sinc = Complex::real(1.0).sub(z2.scale(1.0 / 6.0)).add(z4.scale(1.0 / 120.0)).sub(z6.scale(1.0 / 5040.0));
+ let b = sinc.minus_i().scale(k * factor);
+ let c = sinc.minus_i().scale(k * film_longitudinal_square / factor);
+ let common = b.scale(yi * yt);
+ a.scale(yi - yt).add(common).sub(c).div(a.scale(yi + yt).add(common).add(c))?
+ } else {
+ let yf = qf.scale(1.0 / factor);
+ let r01 = Complex::real(yi).sub(yf).div(Complex::real(yi).add(yf))?;
+ let r12 = yf.sub(Complex::real(yt)).div(yf.add(Complex::real(yt)))?;
+ let decay = (-2.0 * phase.im).exp();
+ let (sine, cosine) = (2.0 * phase.re).sin_cos();
+ let propagation = Complex { re: decay * cosine, im: decay * sine };
+ let second = r12.mul(propagation);
+ r01.add(second).div(Complex::real(1.0).add(r01.mul(second)))?
+ };
+ let power = amplitude.norm_square();
+ if !power.is_finite() || !(0.0..=1.0 + 1e-10).contains(&power) {
+ return Err(GlassModelError::Numerical);
+ }
+ // Only the roundoff of a lossless power sum can exceed one here.
+ Ok(power.min(1.0))
+ };
+ Ok(transmission::Fresnel { s: polarized(false)?, p: polarized(true)?, transmitted_cosine: bare.transmitted_cosine })
+ }
+
+ /// Isotropic GGX visible-normal sampling. Incident points toward the surface;
+ /// macro_normal points into its incident medium. uniforms are facet-u,
+ /// facet-v, Fresnel branch. A returned None is an actual zero contribution;
+ /// retrying until a sample passes would change the estimator.
+ pub fn sample(
+ self,
+ incident: Vec3,
+ macro_normal: Vec3,
+ ni: f64,
+ nt: f64,
+ wavelength_nm: f64,
+ uniforms: [f64; 3],
+ ) -> Result<Option<InterfaceSample>> {
+ self.controls()?;
+ wavelength(wavelength_nm)?;
+ if !valid_ior(ni) || !valid_ior(nt) {
+ return Err(GlassModelError::Ior);
+ }
+ if uniforms.into_iter().any(|u| !u.is_finite() || !(0.0..1.0).contains(&u)) {
+ return Err(GlassModelError::Sample);
+ }
+ let d = direction(incident)?;
+ let n = direction(macro_normal)?;
+ let v = -d;
+ let cv = v.dot(n);
+ if cv < 0.0 {
+ return Err(GlassModelError::Direction);
+ }
+ let smooth = self.roughness == 0.0 || (ni == nt && self.thin_film.is_none_or(|f| f.thickness_nm == 0.0 || f.ior == ni));
+ let m = if smooth {
+ n
+ } else {
+ if cv == 0.0 {
+ return Ok(None);
+ }
+ visible_normal(v, n, self.roughness * self.roughness, [uniforms[0], uniforms[1]])?
+ };
+ let vm = v.dot(m).clamp(0.0, 1.0);
+ let fresnel = self.fresnel(vm, ni, nt, wavelength_nm)?;
+ let reflected = uniforms[2] < fresnel.reflectance() || fresnel.transmitted_cosine.is_none();
+ let (out, probability, crosses) = if reflected {
+ (direction(d + m * (2.0 * vm))?, fresnel.reflectance(), false)
+ } else {
+ let out = transmission::refract(d, m, ni, nt).map_err(|_| GlassModelError::Numerical)?.ok_or(GlassModelError::Numerical)?;
+ (direction(out)?, 1.0 - fresnel.reflectance(), true)
+ };
+ let cl = out.dot(n);
+ if !smooth && ((!crosses && cl <= 0.0) || (crosses && cl >= 0.0)) {
+ return Ok(None);
+ }
+ let radiance = if crosses { (ni / nt).powi(2) } else { 1.0 };
+ let delta = smooth || (crosses && ni == nt);
+ let weight = if smooth { radiance } else { smith_ratio(cv, cl.abs(), self.roughness * self.roughness) * radiance };
+ let pdf = if delta { probability } else { self.evaluate(d, out, n, ni, nt, wavelength_nm)?.pdf };
+ if !weight.is_finite() || weight < 0.0 || !pdf.is_finite() || pdf <= 0.0 {
+ return Err(GlassModelError::Numerical);
+ }
+ Ok(Some(InterfaceSample { direction: out, weight, pdf, crosses, delta }))
+ }
+
+ /// Continuous radiance BSDF and complete reflection/transmission PDF for the
+ /// same VNDF/Fresnel mixture as sample. Rough transmission uses Walter's
+ /// half-vector Jacobian and the radiance (ni/nt)^2 transport conversion.
+ pub fn evaluate(self, incident: Vec3, outgoing: Vec3, macro_normal: Vec3, ni: f64, nt: f64, wavelength_nm: f64) -> Result<InterfaceEvaluation> {
+ self.evaluate_measure(incident, outgoing, macro_normal, ni, nt, wavelength_nm, false)
+ }
+
+ /// Continuous radiance BSDF times the outgoing projected cosine, with the
+ /// same complete mixture PDF as `evaluate`. This is the direct-light
+ /// integrand and avoids dividing by a tiny outgoing cosine only to multiply
+ /// it back. Discrete lobes remain zero in this solid-angle measure.
+ pub fn evaluate_projected(
+ self,
+ incident: Vec3,
+ outgoing: Vec3,
+ macro_normal: Vec3,
+ ni: f64,
+ nt: f64,
+ wavelength_nm: f64,
+ ) -> Result<InterfaceEvaluation> {
+ self.evaluate_measure(incident, outgoing, macro_normal, ni, nt, wavelength_nm, true)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn evaluate_measure(
+ self,
+ incident: Vec3,
+ outgoing: Vec3,
+ macro_normal: Vec3,
+ ni: f64,
+ nt: f64,
+ wavelength_nm: f64,
+ projected: bool,
+ ) -> Result<InterfaceEvaluation> {
+ self.controls()?;
+ // This also validates the actual wavelength/IORs on all zero-lobe paths.
+ self.fresnel(1.0, ni, nt, wavelength_nm)?;
+ let v = -direction(incident)?;
+ let l = direction(outgoing)?;
+ let n = direction(macro_normal)?;
+ let cv = v.dot(n);
+ let cl = l.dot(n);
+ if cv < 0.0 {
+ return Err(GlassModelError::Direction);
+ }
+ if self.roughness == 0.0 || cv == 0.0 || cl == 0.0 || (cl < 0.0 && ni == nt) {
+ return Ok(InterfaceEvaluation::default());
+ }
+ let sum = if cl > 0.0 { v + l } else { v * ni + l * nt };
+ let mut m = direction(sum)?;
+ if m.dot(n) < 0.0 {
+ m = -m;
+ }
+ let vm = v.dot(m);
+ let lm = l.dot(m);
+ if vm <= 0.0 || (cl > 0.0 && lm <= 0.0) || (cl < 0.0 && lm >= 0.0) {
+ return Ok(InterfaceEvaluation::default());
+ }
+ let alpha = self.roughness * self.roughness;
+ let d = ggx_distribution(m, n, alpha);
+ let g1 = smith_g1(cv, alpha);
+ let g2 = g1 * smith_ratio(cv, cl.abs(), alpha);
+ let visible_pdf = d * (2.0 * vm / (cv + smith_root(cv, alpha)));
+ let f = self.fresnel(vm.min(1.0), ni, nt, wavelength_nm)?.reflectance();
+ let outgoing_measure = if projected { 1.0 } else { cl.abs() };
+ let result = if cl > 0.0 {
+ InterfaceEvaluation { value: d * (f * g2 / (4.0 * cv * outgoing_measure)), pdf: visible_pdf * (f / (4.0 * vm)) }
+ } else {
+ let denominator = ni * vm + nt * lm;
+ if denominator == 0.0 {
+ return Ok(InterfaceEvaluation::default());
+ }
+ let jacobian = nt * nt * lm.abs() / (denominator * denominator);
+ InterfaceEvaluation {
+ value: d * ((1.0 - f) * g2 * (vm * lm).abs() * ni * ni / (cv * outgoing_measure * denominator * denominator)),
+ pdf: (1.0 - f) * visible_pdf * jacobian,
+ }
+ };
+ if !result.value.is_finite() || !result.pdf.is_finite() || result.value < 0.0 || result.pdf < 0.0 {
+ return Err(GlassModelError::Numerical);
+ }
+ Ok(result)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn close(actual: f64, expected: f64, tolerance: f64) {
+ assert!((actual - expected).abs() <= tolerance, "{actual} differs from {expected} by more than {tolerance}");
+ }
+ fn film(ior: f64, thickness_nm: f64) -> GlassModel {
+ GlassModel { thin_film: Some(ThinFilm { ior, thickness_nm }), ..Default::default() }
+ }
+ fn radical_inverse(mut bits: u32) -> f64 {
+ bits = bits.reverse_bits();
+ f64::from(bits) / 4294967296.0
+ }
+
+ #[test]
+ fn hard_directional_normal_ggx_response_matches_independent_peak_and_projected_measure() {
+ for roughness in [0.05_f64, 0.2, 0.7, 1.0] {
+ let model = GlassModel { roughness, ..Default::default() };
+ // At normal reflection h=n, G=1, D=1/(pi*r^4), F=((1-1.5)/(1+1.5))^2.
+ let expected = 0.04 / (4.0 * PI * roughness.powi(4));
+ let value = model.evaluate_projected(-Vec3::Z, Vec3::Z, Vec3::Z, 1.0, 1.5, 550.0).unwrap();
+ close(value.value / expected, 1.0, 2e-15);
+ close(value.pdf / expected, 1.0, 2e-15);
+ for uniforms in [[0.01, 0.3, 0.0], [0.1, 0.4, 0.9], [0.4, 0.7, 0.5]] {
+ if let Some(sample) = model.sample(-Vec3::Z, Vec3::Z, 1.0, 1.5, 550.0, uniforms).unwrap() {
+ let projected = model.evaluate_projected(-Vec3::Z, sample.direction, Vec3::Z, 1.0, 1.5, 550.0).unwrap();
+ let unprojected = model.evaluate(-Vec3::Z, sample.direction, Vec3::Z, 1.0, 1.5, 550.0).unwrap();
+ close(projected.value / projected.pdf, sample.weight, 3e-13);
+ close(projected.value / (unprojected.value * sample.direction.z.abs()), 1.0, 3e-13);
+ assert_eq!(projected.pdf, unprojected.pdf);
+ }
+ }
+ }
+ // This peak fits in f64 even though squaring the GGX denominator does not.
+ let tiny = GlassModel { roughness: 1e-50, ..Default::default() };
+ let value = tiny.evaluate_projected(-Vec3::Z, Vec3::Z, Vec3::Z, 1.0, 1.5, 550.0).unwrap();
+ close(value.value / (0.01 / PI * 1e200), 1.0, 2e-15);
+ assert_eq!(GlassModel { roughness: 1e-80, ..Default::default() }.validate(1.5), Err(GlassModelError::Roughness));
+ }
+
+ #[test]
+ fn adjoint_normal_and_flux_area_measures_match_fixed_facet_geometry() {
+ let ng = Vec3::Z;
+ let ns = Vec3::new(0.6, 0.0, 0.8);
+ let wo = Vec3::new(0.0, 0.6, 0.8);
+ let wi = Vec3::new(-0.8, 0.0, 0.6);
+ // Independent scalar dot products: wo.ns=.64, wi.ng=.6,
+ // wo.ng=.8, wi.ns=0. Exact cancellation must survive near grazing too.
+ assert_eq!(importance_normal_correction(-wo, wi, ns, ng).unwrap(), 0.0);
+ let wi = Vec3::new(0.8, 0.0, 0.6);
+ let correction = importance_normal_correction(-wo, wi, ns, ng).unwrap();
+ close(correction, (0.64 * 0.6) / (0.8 * 0.96), 2e-16);
+ let reverse = importance_normal_correction(-wi, wo, ns, ng).unwrap();
+ close(correction * reverse, 1.0, 3e-16);
+ close(surface_normal_measure(wi, ns, ng).unwrap(), 0.96 / 0.6, 3e-16);
+ // A planar photon count already measures wi.ng; the ratio converts it
+ // into wi.ns once, rather than adding a second cosine to deposited flux.
+ let geometric_irradiance = 7.0 * 0.6;
+ close(geometric_irradiance * surface_normal_measure(wi, ns, ng).unwrap(), 7.0 * 0.96, 2e-15);
+ for normal in [Vec3::Z, -Vec3::Z] {
+ close(importance_normal_correction(-wo, wi, normal, ng).unwrap(), 1.0, 0.0);
+ }
+ let grazing = Vec3::new(1.0, 0.0, 1e-300);
+ close(importance_normal_correction(-grazing, grazing, Vec3::X, Vec3::Z).unwrap(), 1.0, 0.0);
+ close(importance_normal_correction(-grazing, grazing, Vec3::Z, Vec3::Z).unwrap(), 1.0, 0.0);
+ let opposite_grazing = Vec3::new(1e-300, 0.0, 1.0);
+ assert_eq!(importance_normal_correction(-grazing, opposite_grazing, Vec3::X, Vec3::Z), Err(GlassModelError::Numerical));
+ close(importance_normal_correction(-wo * 1e300, wi * 1e300, ns * 1e300, ng * 1e300).unwrap(), correction, 3e-16);
+ assert_eq!(surface_normal_measure(Vec3::X, Vec3::Z, Vec3::Z).unwrap(), 0.0);
+ assert_eq!(surface_normal_measure(Vec3::ZERO, ns, ng), Err(GlassModelError::Direction));
+ assert_eq!(importance_normal_correction(Vec3::new(f64::NAN, 0.0, 0.0), wi, ns, ng), Err(GlassModelError::Direction));
+ }
+
+ #[test]
+ fn analog_volume_photon_measure_has_correct_density_units_and_sigma_cancellation() {
+ let radius = 2.5_f64;
+ let sigma = 0.2;
+ let ball_volume = 4.0 * PI * radius.powi(3) / 3.0;
+ let kernel = volume_photon_kernel(radius, sigma).unwrap();
+ close(kernel * ball_volume * sigma, 1.0, 2e-16);
+ // A homogeneous field with fluence Phi deposits sigma*Phi collisions per
+ // volume; an isotropic analog camera collision must recover Phi/(4*pi).
+ let fluence = 11.0;
+ let isotropic_phase = 1.0 / (4.0 * PI);
+ close(kernel * (sigma * fluence * ball_volume) * isotropic_phase, fluence * isotropic_phase, 3e-16);
+ close(volume_photon_kernel(radius * 2.0, sigma).unwrap() * 8.0, kernel, 0.0);
+ close(volume_photon_kernel(radius, sigma * 2.0).unwrap() * 2.0, kernel, 0.0);
+ close(volume_photon_kernel(1e100, 1e-300).unwrap(), 3.0 / (4.0 * PI), 2e-16);
+ // Unit conversion mm -> metre: radius /1000 and sigma *1000; an
+ // inverse-area estimator consequently gains 10^6, without changing flux.
+ close(volume_photon_kernel(radius / 1000.0, sigma * 1000.0).unwrap() / kernel, 1e6, 3e-10);
+ for (r, s) in [(0.0, sigma), (-1.0, sigma), (f64::INFINITY, sigma), (radius, 0.0), (radius, f64::NAN), (1e-200, sigma)] {
+ assert_eq!(volume_photon_kernel(r, s), Err(GlassModelError::Numerical));
+ }
+ }
+
+ #[test]
+ fn photon_hg_receiver_angle_uses_physical_forward_propagation() {
+ let medium = crate::transmission::subsurface::Subsurface { scattering_per_mm: 0.2, anisotropy: 0.6 };
+ let incoming_light = Vec3::Z; // The photon's physical travel is -Z.
+ let camera_incident = Vec3::Z; // The scattered travel toward the eye is -Z.
+ let forward_cosine = camera_incident.dot(incoming_light);
+ let backward_cosine = (-camera_incident).dot(incoming_light);
+ let forward = medium.phase(forward_cosine).unwrap();
+ let backward = medium.phase(backward_cosine).unwrap();
+ let g = medium.anisotropy;
+ close(forward, (1.0 + g) / (4.0 * PI * (1.0 - g).powi(2)), 2e-15);
+ close(backward, (1.0 - g) / (4.0 * PI * (1.0 + g).powi(2)), 2e-17);
+ close(forward / backward, ((1.0 + g) / (1.0 - g)).powi(3), 2e-13);
+ assert!(forward > backward);
+ }
+
+ #[test]
+ fn one_record_uniform_receiver_reservoir_is_unbiased_for_every_bounded_path_length() {
+ // Count all replacement decisions exactly, without Monte Carlo or a
+ // production reservoir helper: stage k has k equally likely outcomes,
+ // one replaces the record and k-1 retain it. At k<=16, k! fits in u64.
+ let mut histories = vec![1_u64];
+ let mut total = 1_u64;
+ for k in 1..=16_usize {
+ if k > 1 {
+ for count in &mut histories {
+ *count *= (k - 1) as u64;
+ }
+ histories.push(total);
+ total *= k as u64;
+ }
+ assert_eq!(histories.iter().copied().sum::<u64>(), total);
+ let mut expected_numerator = 0_u128;
+ let mut reference_sum = 0_u128;
+ for (index, &count) in histories.iter().enumerate() {
+ assert_eq!(count * k as u64, total);
+ let flux = (index + 2).pow(2) as u128;
+ let receiver_response = (3 * index + 1) as u128;
+ reference_sum += flux * receiver_response;
+ expected_numerator += u128::from(count) * k as u128 * flux * receiver_response;
+ }
+ assert_eq!(expected_numerator, u128::from(total) * reference_sum);
+ // Dividing by launched paths rather than retained records also
+ // preserves zero-deposit paths: append one empty launch explicitly.
+ close(expected_numerator as f64 / total as f64 / 2.0, reference_sum as f64 / 2.0, 0.0);
+ }
+ }
+
+ #[test]
+ fn bounded_models_round_trip_and_refuse_hostile_values() {
+ let model = GlassModel {
+ roughness: 0.3,
+ dispersion: Some(Dispersion { abbe_number: 60.0 }),
+ thin_film: Some(ThinFilm { ior: 1.38, thickness_nm: 285.0 }),
+ };
+ model.validate(1.5).unwrap();
+ assert_eq!(serde_json::from_value::<GlassModel>(serde_json::to_value(model).unwrap()).unwrap(), model);
+ assert_eq!(serde_json::from_str::<GlassModel>("{}").unwrap(), GlassModel::default());
+ assert!(serde_json::from_str::<GlassModel>(r#"{"roughnes":0.5}"#).is_err());
+ assert!(serde_json::from_str::<GlassModel>(r#"{"dispersion":{"abbe_number":40,"unknown":0}}"#).is_err());
+ for roughness in [-1.0, f64::NAN, f64::INFINITY, 1.1, f64::MIN_POSITIVE] {
+ assert_eq!(GlassModel { roughness, ..Default::default() }.validate(1.5), Err(GlassModelError::Roughness));
+ }
+ for abbe_number in [0.0, 4.99, 200.1, f64::NAN, f64::INFINITY] {
+ assert_eq!(
+ GlassModel { dispersion: Some(Dispersion { abbe_number }), ..Default::default() }.validate(1.5),
+ Err(GlassModelError::Dispersion)
+ );
+ }
+ for bad in [
+ ThinFilm { ior: 0.99, thickness_nm: 10.0 },
+ ThinFilm { ior: 1.4, thickness_nm: -1.0 },
+ ThinFilm { ior: 1.4, thickness_nm: f64::NAN },
+ ThinFilm { ior: 1.4, thickness_nm: 100001.0 },
+ ] {
+ assert_eq!(GlassModel { thin_film: Some(bad), ..Default::default() }.validate(1.5), Err(GlassModelError::Film));
+ }
+ assert!(!film(1.4, 0.0).spectral());
+ assert!(film(1.4, 1.0).spectral());
+ assert!(film(1.4, 0.0).is_identity());
+ assert!(GlassModel { dispersion: Some(Dispersion { abbe_number: 100.0 }), ..Default::default() }.spectral());
+ }
+
+ #[test]
+ fn cauchy_fit_matches_independent_abbe_definition_and_visible_ordering() {
+ for (nd, vd) in [(1.33, 55.0), (1.5, 60.0), (1.8, 25.0), (2.0, 12.0)] {
+ let model = GlassModel { dispersion: Some(Dispersion { abbe_number: vd }), ..Default::default() };
+ close(model.ior(nd, D_LINE_NM).unwrap(), nd, 1e-15);
+ let f = model.ior(nd, F_LINE_NM).unwrap();
+ let c = model.ior(nd, C_LINE_NM).unwrap();
+ close((nd - 1.0) / (f - c), vd, 2e-11);
+ let [r, g, b] = WAVELENGTHS_NM.map(|nm| model.ior(nd, nm).unwrap());
+ assert!(b > g && g > r);
+ for nm in [MIN_WAVELENGTH_NM, MAX_WAVELENGTH_NM] {
+ close(model.ior(1.0, nm).unwrap(), 1.0, 0.0);
+ }
+ }
+ let strong = GlassModel { dispersion: Some(Dispersion { abbe_number: 5.0 }), ..Default::default() };
+ assert_eq!(strong.validate(3.0), Err(GlassModelError::Dispersion));
+ assert_eq!(strong.ior(1.5, 1000.0), Err(GlassModelError::Wavelength));
+ }
+
+ #[test]
+ fn no_film_and_zero_thickness_preserve_bare_fresnel_exactly() {
+ for (ni, nt) in [(1.0, 1.5), (1.5, 1.0), (1.5, 1.5)] {
+ for cosine in [0.0, 0.001, 0.3, 0.8, 1.0] {
+ let bare = transmission::fresnel(cosine, ni, nt).unwrap();
+ for model in [GlassModel::default(), film(1.38, 0.0), film(ni, 500.0), film(nt, 500.0)] {
+ assert_eq!(model.fresnel(cosine, ni, nt, 550.0).unwrap(), bare);
+ }
+ }
+ }
+ let brewster_cosine = (1.5_f64).atan().cos();
+ let brewster = GlassModel::default().fresnel(brewster_cosine, 1.0, 1.5, 550.0).unwrap();
+ assert!(brewster.p < 1e-30 && brewster.s > 0.1);
+ assert_eq!(film(1.38, 500.0).fresnel(0.3, 1.5, 1.0, 550.0).unwrap().transmitted_cosine, None);
+ }
+
+ #[test]
+ fn airy_quarter_wave_antireflection_and_periodicity_match_analytic_limits() {
+ let nf = 1.5_f64.sqrt();
+ let quarter = film(nf, 550.0 / (4.0 * nf));
+ let response = quarter.fresnel(1.0, 1.0, 1.5, 550.0).unwrap();
+ assert!(response.s < 1e-28 && response.p < 1e-28);
+ for cosine in [0.2, 0.6, 1.0] {
+ let cosine_film = (1.0 - (1.0 - cosine * cosine) / 1.38_f64.powi(2)).sqrt();
+ let period = 550.0 / (2.0 * 1.38 * cosine_film);
+ let a = film(1.38, 285.0).fresnel(cosine, 1.0, 1.5, 550.0).unwrap();
+ let b = film(1.38, 285.0 + period).fresnel(cosine, 1.0, 1.5, 550.0).unwrap();
+ close(a.s, b.s, 2e-14);
+ close(a.p, b.p, 2e-14);
+ assert_eq!(a.transmitted_cosine, transmission::fresnel(cosine, 1.0, 1.5).unwrap().transmitted_cosine);
+ }
+ }
+
+ #[test]
+ fn film_evanescence_tunnels_and_critical_angle_is_continuous() {
+ let thin = film(1.0, 1e-5).fresnel(0.5, 1.5, 1.5, 550.0).unwrap();
+ let medium = film(1.0, 100.0).fresnel(0.5, 1.5, 1.5, 550.0).unwrap();
+ let thick = film(1.0, 100000.0).fresnel(0.5, 1.5, 1.5, 550.0).unwrap();
+ assert!(thin.reflectance() < 1e-12);
+ assert!(medium.reflectance() > 0.1 && medium.reflectance() < 1.0);
+ close(thick.s, 1.0, 1e-14);
+ close(thick.p, 1.0, 1e-14);
+ let critical_cosine = 5.0_f64.sqrt() / 3.0;
+ let at = film(1.0, 200.0).fresnel(critical_cosine, 1.5, 1.5, 550.0).unwrap();
+ for offset in [-1e-9, 1e-9] {
+ let near = film(1.0, 200.0).fresnel(critical_cosine + offset, 1.5, 1.5, 550.0).unwrap();
+ close(at.s, near.s, 1e-7);
+ close(at.p, near.p, 1e-7);
+ }
+ assert!(at.s.is_finite() && at.p.is_finite());
+ }
+
+ #[test]
+ fn film_power_is_bounded_and_reciprocal_at_matching_optical_angles() {
+ for thickness in [1e-8, 50.0, 285.0, 10000.0, 100000.0] {
+ for nm in WAVELENGTHS_NM {
+ for cosine in [0.01, 0.2, 0.7, 1.0] {
+ let model = film(1.1, thickness);
+ let forward = model.fresnel(cosine, 1.0, 1.5, nm).unwrap();
+ assert!((0.0..=1.0).contains(&forward.s) && (0.0..=1.0).contains(&forward.p));
+ let reverse = model.fresnel(forward.transmitted_cosine.unwrap(), 1.5, 1.0, nm).unwrap();
+ close(forward.s, reverse.s, 1e-10);
+ close(forward.p, reverse.p, 1e-10);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn rough_sampling_weights_equal_continuous_bsdf_over_full_pdf() {
+ for roughness in [0.12, 0.5, 1.0] {
+ for (ni, nt) in [(1.0, 1.5), (1.5, 1.0)] {
+ for cosine in [0.2, 0.7, 1.0] {
+ let incident = Vec3::new((1.0_f64 - cosine * cosine).sqrt(), 0.0, -cosine);
+ let model = GlassModel { roughness, thin_film: Some(ThinFilm { ior: 1.38, thickness_nm: 270.0 }), ..Default::default() };
+ let mut accepted = 0;
+ for i in 0..2048_u32 {
+ let random =
+ [(f64::from(i) + 0.5) / 2048.0, radical_inverse(i), radical_inverse(i.wrapping_mul(1664525).wrapping_add(1013904223))];
+ if let Some(sample) = model.sample(incident, Vec3::Z, ni, nt, 550.0, random).unwrap() {
+ assert!(!sample.delta);
+ assert_eq!(sample.crosses, sample.direction.z < 0.0);
+ let eval = model.evaluate(incident, sample.direction, Vec3::Z, ni, nt, 550.0).unwrap();
+ close(sample.pdf, eval.pdf, sample.pdf * 1e-12 + 1e-14);
+ close(sample.weight, eval.value * sample.direction.z.abs() / eval.pdf, sample.weight * 2e-8 + 1e-10);
+ assert!(sample.weight >= 0.0 && sample.weight <= (ni / nt).powi(2).max(1.0) * (1.0 + 1e-12));
+ accepted += 1;
+ }
+ }
+ assert!(accepted > 200);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn visible_normal_density_integrates_to_one_and_rough_furnace_cannot_gain_energy() {
+ let nz = 256_u32;
+ let np = 512_u32;
+ let solid_angle = TAU / f64::from(nz * np);
+ for alpha in [0.3, 0.7, 1.0] {
+ for cosine in [0.2, 0.7, 1.0] {
+ let v = Vec3::new((1.0_f64 - cosine * cosine).sqrt(), 0.0, cosine);
+ let mut integral = 0.0;
+ for z in 0..nz {
+ let z = (f64::from(z) + 0.5) / f64::from(nz);
+ let radius = (1.0 - z * z).sqrt();
+ for phi in 0..np {
+ let (s, c) = (TAU * (f64::from(phi) + 0.5) / f64::from(np)).sin_cos();
+ let m = Vec3::new(radius * c, radius * s, z);
+ integral += ggx_distribution(m, Vec3::Z, alpha) * smith_g1(cosine, alpha) * v.dot(m).max(0.0) / cosine;
+ }
+ }
+ close(integral * solid_angle, 1.0, 0.002);
+ let model = GlassModel { roughness: alpha.sqrt(), ..Default::default() };
+ let mut furnace = 0.0;
+ for i in 0..8192_u32 {
+ let random =
+ [(f64::from(i) + 0.5) / 8192.0, radical_inverse(i), radical_inverse(i.wrapping_mul(1664525).wrapping_add(1013904223))];
+ if let Some(sample) = model.sample(-v, Vec3::Z, 1.0, 1.5, 550.0, random).unwrap() {
+ furnace += sample.weight * if sample.crosses { 1.5 * 1.5 } else { 1.0 };
+ }
+ }
+ assert!((0.45..=1.000000001).contains(&(furnace / 8192.0)), "rough single-scattering furnace={}", furnace / 8192.0);
+ }
+ }
+ }
+
+ #[test]
+ fn matched_indices_and_zero_roughness_retain_discrete_physical_limits() {
+ let incident = direction(Vec3::new(0.8, 0.0, -0.6)).unwrap();
+ for roughness in [0.0, 0.5, 1.0] {
+ let model = GlassModel { roughness, ..Default::default() };
+ let sample = model.sample(incident, Vec3::Z, 1.5, 1.5, 550.0, [0.7, 0.2, 0.1]).unwrap().unwrap();
+ assert!(sample.delta && sample.crosses);
+ close(sample.weight, 1.0, 0.0);
+ close((sample.direction - incident).len(), 0.0, 1e-15);
+ }
+ let model = GlassModel::default();
+ let reflected = model.sample(incident, Vec3::Z, 1.0, 1.5, 550.0, [0.0; 3]).unwrap().unwrap();
+ assert!(reflected.delta && !reflected.crosses);
+ close(reflected.weight, 1.0, 0.0);
+ let transmitted = model.sample(incident, Vec3::Z, 1.0, 1.5, 550.0, [0.9; 3]).unwrap().unwrap();
+ assert!(transmitted.delta && transmitted.crosses);
+ close(transmitted.weight, 1.0 / 2.25, 1e-15);
+ assert_eq!(model.sample(incident, Vec3::Z, 1.0, 1.5, 550.0, [1.0, 0.0, 0.0]), Err(GlassModelError::Sample));
+ }
+}
+
+fn visible_normal(v: Vec3, n: Vec3, alpha: f64, u: [f64; 2]) -> Result<Vec3> {
+ let tangent = direction(if n.z.abs() < 0.9 { Vec3::Z.cross(n) } else { Vec3::X.cross(n) })?;
+ let bitangent = n.cross(tangent);
+ let stretched = direction(Vec3::new(alpha * v.dot(tangent), alpha * v.dot(bitangent), v.dot(n)))?;
+ let side = if stretched.x == 0.0 && stretched.y == 0.0 { Vec3::X } else { direction(Vec3::new(-stretched.y, stretched.x, 0.0))? };
+ let vertical = stretched.cross(side);
+ let radius = u[0].sqrt();
+ let (sine, cosine) = (TAU * u[1]).sin_cos();
+ let x = radius * cosine;
+ let mix = 0.5 * (1.0 + stretched.z);
+ let y = (1.0 - mix) * (1.0 - x * x).max(0.0).sqrt() + mix * radius * sine;
+ let height = (1.0 - x * x - y * y).max(0.0).sqrt();
+ let hemisphere = side * x + vertical * y + stretched * height;
+ let local = direction(Vec3::new(alpha * hemisphere.x, alpha * hemisphere.y, hemisphere.z.max(0.0)))?;
+ direction(tangent * local.x + bitangent * local.y + n * local.z)
+}
+fn ggx_distribution(m: Vec3, n: Vec3, alpha: f64) -> f64 {
+ let cosine = m.dot(n);
+ if cosine <= 0.0 {
+ return 0.0;
+ }
+ let sine = m.cross(n);
+ let denominator = sine.dot(sine) + alpha * alpha * cosine * cosine;
+ let root = (alpha / denominator) / PI.sqrt();
+ root * root
+}
+fn smith_root(cosine: f64, alpha: f64) -> f64 {
+ (cosine * cosine + alpha * alpha * (1.0 - cosine * cosine).max(0.0)).sqrt()
+}
+fn smith_g1(cosine: f64, alpha: f64) -> f64 {
+ 2.0 * cosine / (cosine + smith_root(cosine, alpha))
+}
+fn smith_ratio(cv: f64, cl: f64, alpha: f64) -> f64 {
+ if cv <= 0.0 || cl <= 0.0 {
+ return 0.0;
+ }
+ let sv = smith_root(cv, alpha);
+ let sl = smith_root(cl, alpha);
+ cl * (cv + sv) / (sv * cl + sl * cv)
+}
+
+#[derive(Clone, Copy)]
+struct Complex {
+ re: f64,
+ im: f64,
+}
+impl Complex {
+ fn real(re: f64) -> Self {
+ Self { re, im: 0.0 }
+ }
+ fn add(self, b: Self) -> Self {
+ Self { re: self.re + b.re, im: self.im + b.im }
+ }
+ fn sub(self, b: Self) -> Self {
+ Self { re: self.re - b.re, im: self.im - b.im }
+ }
+ fn scale(self, b: f64) -> Self {
+ Self { re: self.re * b, im: self.im * b }
+ }
+ fn mul(self, b: Self) -> Self {
+ Self { re: self.re * b.re - self.im * b.im, im: self.re * b.im + self.im * b.re }
+ }
+ fn minus_i(self) -> Self {
+ Self { re: self.im, im: -self.re }
+ }
+ fn norm_square(self) -> f64 {
+ self.re * self.re + self.im * self.im
+ }
+ fn div(self, b: Self) -> Result<Self> {
+ let denominator = b.norm_square();
+ if !denominator.is_finite() || denominator <= 0.0 {
+ return Err(GlassModelError::Numerical);
+ }
+ let value = Self { re: (self.re * b.re + self.im * b.im) / denominator, im: (self.im * b.re - self.re * b.im) / denominator };
+ if !value.re.is_finite() || !value.im.is_finite() {
+ return Err(GlassModelError::Numerical);
+ }
+ Ok(value)
+ }
+}
diff --git a/crates/render/src/job/caustics.rs b/crates/render/src/job/caustics.rs
new file mode 100644
index 0000000000..d774fe7733
--- /dev/null
+++ b/crates/render/src/job/caustics.rs
@@ -0,0 +1,53 @@
+//! Opt-in finite-radius density estimation for delta-light optical caustics.
+//! Photon count and radius are explicit quality controls, not a convergence certificate.
+use super::{ErrorCode, JobError, Result};
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct CausticOptions {
+ pub photons: u32,
+ pub radius_mm: f64,
+ pub max_depth: u8,
+ pub seed: u32,
+}
+impl Default for CausticOptions {
+ fn default() -> Self {
+ Self { photons: 16384, radius_mm: 1.0, max_depth: 16, seed: 81 }
+ }
+}
+impl CausticOptions {
+ pub fn validate(self) -> Result<()> {
+ if !(1..=65536).contains(&self.photons)
+ || !self.radius_mm.is_finite()
+ || !(1e-6..=1e6).contains(&self.radius_mm)
+ || !(1..=16).contains(&self.max_depth)
+ {
+ return Err(JobError::new(
+ ErrorCode::InvalidRequest,
+ "caustics require 1..65536 photons, finite radius 0.000001..1000000 mm and 1..16 light-path events",
+ ));
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn photon_options_round_trip_and_reject_unbounded_work_and_radius() {
+ let valid = CausticOptions::default();
+ valid.validate().unwrap();
+ assert_eq!(serde_json::from_value::<CausticOptions>(serde_json::to_value(valid).unwrap()).unwrap(), valid);
+ for photons in [0, 65537, u32::MAX] {
+ assert!(CausticOptions { photons, ..valid }.validate().is_err());
+ }
+ for radius_mm in [f64::NAN, f64::INFINITY, 0.0, -1.0, 1e-7, 1e6 + 1.0] {
+ assert!(CausticOptions { radius_mm, ..valid }.validate().is_err());
+ }
+ for max_depth in [0, 17, u8::MAX] {
+ assert!(CausticOptions { max_depth, ..valid }.validate().is_err());
+ }
+ }
+}
diff --git a/crates/render/src/job/host.rs b/crates/render/src/job/host.rs
index f63a2645ab..8a7a548939 100644
--- a/crates/render/src/job/host.rs
+++ b/crates/render/src/job/host.rs
@@ -1631,6 +1631,15 @@ impl ImageHost {
self.validate_integrator(request.integrator)?;
options.validate()?;
if let Some(executor) = &self.0.executor {
+ let modeled = |t: Option<crate::transmission::Transmission>| t.is_some_and(|t| t.model().is_some());
+ if scene.meshes.iter().any(|b| modeled(b.transmission) || b.faces.iter().any(|f| modeled(f.transmission)))
+ && !executor.supports_glass_models()
+ {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement the authored advanced Glass models"));
+ }
+ if options.caustics.is_some() && !executor.supports_caustics() {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "registered executor does not implement delta-light caustic photons"));
+ }
if request.raytrace.is_some() {
return Err(JobError::new(ErrorCode::InvalidRequest, "registered executors do not accept CPU raytrace options"));
}
diff --git a/crates/render/src/job/host_regrade_tests.rs b/crates/render/src/job/host_regrade_tests.rs
index 241b46c2b5..5e2260e8ce 100644
--- a/crates/render/src/job/host_regrade_tests.rs
+++ b/crates/render/src/job/host_regrade_tests.rs
@@ -207,7 +207,8 @@ fn fixed_cpu_volume_request_header_is_prepaid_on_completed_and_cancelled_regrade
let header = ImageRequest::fixed_cpu_metadata_bytes();
assert_eq!(
header,
- (std::mem::size_of::<Option<super::super::volume::HomogeneousVolume>>()
+ (std::mem::size_of::<Option<super::super::CausticOptions>>()
+ + std::mem::size_of::<Option<super::super::volume::HomogeneousVolume>>()
+ std::mem::size_of::<Option<Box<super::super::Sun>>>()
+ std::mem::size_of::<Option<Box<super::super::CpuSky>>>()) as u64
);
diff --git a/crates/render/src/job/host_tests.rs b/crates/render/src/job/host_tests.rs
index f7a1ce4100..b4632de2d4 100644
--- a/crates/render/src/job/host_tests.rs
+++ b/crates/render/src/job/host_tests.rs
@@ -781,6 +781,34 @@ fn probe_host(estimated: u64) -> (CpuHost, Arc<AtomicU64>) {
(host, admitted_at_drop)
}
+#[test]
+fn unqualified_executors_refuse_glass_models_and_caustics_before_acquiring_a_lease() {
+ let (host, _) = probe_host(1024);
+ let options = JobOptions { caustics: Some(Default::default()), ..Default::default() };
+ let error = host.admit(&empty(), &request(), options).unwrap_err();
+ assert_eq!(error.code, ErrorCode::InvalidRequest);
+ assert!(error.message.contains("caustic photons"));
+ assert_eq!(host.admitted_bytes(), 0);
+ let mut scene = empty();
+ scene.meshes.push(crate::ProductMesh {
+ name: "Original unsupported-model fixture".into(),
+ mesh: Arc::new(Mesh::default()),
+ color: [255; 3],
+ opacity: 1.0,
+ surface: None,
+ transmission: Some(
+ crate::transmission::Transmission::new(solidcore_record::Vec3::ZERO, None)
+ .unwrap()
+ .with_model(crate::glass_model::GlassModel { roughness: 0.3, ..Default::default() })
+ .unwrap(),
+ ),
+ faces: Vec::new(),
+ });
+ let error = host.admit(&scene, &request(), JobOptions::default()).unwrap_err();
+ assert!(error.message.contains("advanced Glass models"));
+ assert_eq!(host.admitted_bytes(), 0);
+}
+
#[test]
fn a_completed_task_is_dropped_while_its_full_reservation_still_pays_for_it() {
let estimated = 1 << 20;
@@ -1682,7 +1710,8 @@ fn celestial_cancelled_capture_retains_only_exact_boxes_and_fixed_header_until_l
let fixed = ImageRequest::fixed_cpu_metadata_bytes();
assert_eq!(
fixed,
- (std::mem::size_of::<Option<Box<Sun>>>()
+ (std::mem::size_of::<Option<super::super::CausticOptions>>()
+ + std::mem::size_of::<Option<Box<Sun>>>()
+ std::mem::size_of::<Option<Box<CpuSky>>>()
+ std::mem::size_of::<Option<super::super::volume::HomogeneousVolume>>()) as u64
);
@@ -1765,6 +1794,7 @@ mod prepared_optical_submission {
lights: Some(Vec::new()),
environment: Some(crate::job::RaytraceEnvironmentOptions { color: [1.0; 3], intensity: 1.0 }),
dielectrics: vec![DielectricOptions {
+ model: None,
body_index: 0,
body_name: "captured box".into(),
boundary: DielectricBoundary::ClosedBox,
diff --git a/crates/render/src/job/image_tests.rs b/crates/render/src/job/image_tests.rs
index 79e38310fe..6208e33784 100644
--- a/crates/render/src/job/image_tests.rs
+++ b/crates/render/src/job/image_tests.rs
@@ -178,9 +178,9 @@ fn invalid_sizes_indices_opacity_and_large_work_lists_fail_without_a_frame() {
#[test]
fn registered_executor_geometry_admission_excludes_the_cpu_raster_estimate() {
- // A library-bounded source: about 100 MiB of face appearances on a small mesh at the
+ // A library-bounded source: about 120 MiB of face appearances on a small mesh at the
// largest image. Its CPU raster estimate is above 384 MiB at a registered executor's cap.
- let count = (100 * 1024 * 1024 / std::mem::size_of::<FaceAppearance>()).min(1_000_000);
+ let count = (120 * 1024 * 1024 / std::mem::size_of::<FaceAppearance>()).min(1_000_000);
let mut body = square("appearances", [200; 3], 1.0, Vec3::ZERO);
body.faces = vec![FaceAppearance { transmission: None, face: 0, color: [200; 3], opacity: 1.0, surface: None }; count];
let source = scene(vec![body]);
diff --git a/crates/render/src/job/mod.rs b/crates/render/src/job/mod.rs
index 158219dd46..e37bad7ff4 100644
--- a/crates/render/src/job/mod.rs
+++ b/crates/render/src/job/mod.rs
@@ -15,6 +15,7 @@ use crate::{BackendId, Camera, ExecutorId};
pub mod adaptive;
pub mod aging;
pub mod bloom;
+pub mod caustics;
mod cpu_budget;
mod cpu_path;
mod cpu_sky;
@@ -44,6 +45,7 @@ mod rt2_tests;
pub mod textures;
pub mod volume;
+pub use caustics::CausticOptions;
pub use cpu_budget::{CpuBudget, CpuBudgetLimits, MAX_CPU_BODIES, MAX_CPU_SAMPLES_PER_PIXEL, MAX_CPU_TRIANGLES, MAX_CPU_WORK, NATIVE_CPU_POOL_BYTES};
pub use cpu_path::CpuPathOptions;
pub use cpu_sky::CpuSky;
@@ -73,6 +75,8 @@ pub const MAX_GPU_DIELECTRICS: usize = 32;
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct JobOptions {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub caustics: Option<CausticOptions>,
#[serde(skip_serializing_if = "aging::AgingStack::is_empty")]
pub aging: aging::AgingStack,
pub nested_media: bool,
@@ -103,6 +107,7 @@ pub struct JobOptions {
impl Default for JobOptions {
fn default() -> Self {
Self {
+ caustics: None,
aging: Default::default(),
nested_media: false,
volume: None,
@@ -165,6 +170,9 @@ impl JobOptions {
.ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "sampling pass target overflow"))
}
pub fn validate(&self) -> Result<()> {
+ if let Some(caustics) = self.caustics {
+ caustics.validate()?;
+ }
self.aging.validate()?;
if let Some(volume) = self.volume {
volume.validate()?;
@@ -248,6 +256,12 @@ impl ImageWork for ImageTask {
/// Device-independent executor boundary. The host owns admission leases and publication;
/// an executor owns computation only. GPU implementations live above the render crate.
pub trait ImageExecutor: Send + Sync {
+ fn supports_glass_models(&self) -> bool {
+ false
+ }
+ fn supports_caustics(&self) -> bool {
+ false
+ }
/// Pure metadata: complete passes this request can publish (including adaptive pilots).
/// The host prepays at most two immutable PNG snapshots in addition to executor work.
fn preview_samples(&self, _options: JobOptions) -> Option<u32> {
@@ -655,6 +669,8 @@ pub enum DielectricBoundary {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DielectricOptions {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub model: Option<crate::glass_model::GlassModel>,
/// Homogeneous elastic scattering inside a certified closed Path medium.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subsurface: Option<crate::transmission::subsurface::Subsurface>,
@@ -793,6 +809,8 @@ pub fn validate_cpu_denoise_image(width: u32, height: u32) -> Result<()> {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RaytraceOptions {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub caustics: Option<CausticOptions>,
/// One bounded world-space participating medium, available with explicit Path.
#[serde(skip_serializing_if = "Option::is_none")]
pub volume: Option<volume::HomogeneousVolume>,
@@ -850,6 +868,7 @@ pub struct RaytraceOptions {
impl Default for RaytraceOptions {
fn default() -> Self {
Self {
+ caustics: None,
volume: None,
sun: None,
sky: None,
@@ -1108,6 +1127,12 @@ impl RaytraceOptions {
}
pub fn validate(&self) -> Result<()> {
let _ = self.retained_volume_bytes()?;
+ if let Some(caustics) = self.caustics {
+ caustics.validate()?;
+ if self.path.is_none() {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "CPU caustics require explicit Indirect lighting"));
+ }
+ }
if self.volume.as_ref().is_some_and(|v| v.active()) {
if self.path.is_none() {
return Err(JobError::new(ErrorCode::InvalidRequest, "CPU Atmosphere requires explicit Indirect lighting"));
@@ -1194,6 +1219,15 @@ impl RaytraceOptions {
return Err(JobError::new(ErrorCode::InvalidRequest, "at most eight dielectric overrides"));
}
for (index, input) in self.dielectrics.iter().enumerate() {
+ if let Some(model) = input.model {
+ model.validate(input.ior).map_err(|e| JobError::new(ErrorCode::InvalidRequest, e.to_string()))?;
+ if self.path.is_none() {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "advanced Glass models require CPU Indirect lighting"));
+ }
+ if input.boundary == DielectricBoundary::ThinSheet && input.shadow_transmission && model.roughness > 0.0 {
+ return Err(JobError::new(ErrorCode::InvalidRequest, "rough thin-sheet Glass requires disabled straight transmitted shadows"));
+ }
+ }
if let Some(scattering) = input.subsurface {
scattering.validate().map_err(|error| JobError::new(ErrorCode::InvalidRequest, error.to_string()))?;
if self.path.is_none() || input.boundary == DielectricBoundary::ThinSheet {
@@ -1403,7 +1437,8 @@ impl ImageRequest {
/// Fixed inline request growth is prepaid even when raytrace is None.
/// Queued/worker state cannot fund the retained Record after work release.
pub const fn fixed_cpu_metadata_bytes() -> u64 {
- (std::mem::size_of::<Option<volume::HomogeneousVolume>>()
+ (std::mem::size_of::<Option<CausticOptions>>()
+ + std::mem::size_of::<Option<volume::HomogeneousVolume>>()
+ std::mem::size_of::<Option<Box<Sun>>>()
+ std::mem::size_of::<Option<Box<CpuSky>>>()) as u64
}
@@ -1504,6 +1539,7 @@ mod runtime_request_roundtrip_tests {
};
RaytraceOptions { progressive, area_lights: Some(vec![area]), ..Default::default() }.validate().unwrap();
let dielectric = DielectricOptions {
+ model: None,
shadow_transmission: false,
subsurface: None,
body_index: 0,
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index c4b46531ee..8e346c9840 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -12,6 +12,7 @@ pub mod clear_coat;
mod curve_display;
pub mod film;
mod gif;
+pub mod glass_model;
pub mod hatch;
pub mod job;
pub mod lighting;
diff --git a/crates/render/src/raytrace/dielectric.rs b/crates/render/src/raytrace/dielectric.rs
index 9dc1a93e41..efc051d0f7 100644
--- a/crates/render/src/raytrace/dielectric.rs
+++ b/crates/render/src/raytrace/dielectric.rs
@@ -99,6 +99,51 @@ pub(super) fn thin_sheet(direction: Vec3, normal: Vec3, material: &DielectricOpt
Ok((Interface { transmitted: Some(direction), ..optics }, Vec3::new(rr, rg, rb), Vec3::new(tr, tg, tb)))
}
+/// Three-band parallel-sheet closure. Smooth sheet directions are wavelength
+/// independent, so RGB coefficients share one scalar branch probability and the
+/// existing transmitted-shadow MIS chain; no hero wavelength is needed here.
+pub(super) fn modeled_sheet(direction: Vec3, normal: Vec3, material: &DielectricOptions) -> Result<(Interface, Vec3, Vec3)> {
+ let Some(model) = material.model.filter(|model| model.spectral()) else { return thin_sheet(direction, normal, material) };
+ if model.roughness > 0.0 {
+ return Err(TraceError::InvalidInput("rough thin-sheet transport requires its virtual interface walk"));
+ }
+ let direction = unit(direction).ok_or(TraceError::InvalidInput("modeled sheet incident direction"))?;
+ let normal = unit(normal).ok_or(TraceError::InvalidInput("modeled sheet normal"))?;
+ let optics = interface(direction, normal, 1.0, material.ior)?;
+ let mut reflection = [0.0; 3];
+ let mut transmission = [0.0; 3];
+ for (channel, wavelength) in crate::glass_model::WAVELENGTHS_NM.into_iter().enumerate() {
+ let ior = model.ior(material.ior, wavelength).map_err(|_| TraceError::InvalidInput("modeled sheet spectral IOR"))?;
+ let f = model
+ .fresnel((-direction.dot(normal)).clamp(0.0, 1.0), 1.0, ior, wavelength)
+ .map_err(|_| TraceError::InvalidInput("modeled sheet spectral Fresnel"))?;
+ let distance = if material.thickness_mm == 0.0 {
+ 0.0
+ } else if let Some(cosine) = f.transmitted_cosine.filter(|cosine| *cosine > 0.0) {
+ material.thickness_mm / cosine
+ } else {
+ return Err(TraceError::InvalidInput("modeled sheet has no finite grazing optical distance"));
+ };
+ if !distance.is_finite() || !(0.0..=super::MAX_DISTANCE_MM).contains(&distance) {
+ return Err(TraceError::InvalidInput("modeled sheet optical distance exceeds finite bounds"));
+ }
+ let a = (-material.absorption_per_mm[channel] * distance).exp();
+ let series = |r: f64| {
+ let denominator = 1.0 - r * r * a * a;
+ if denominator <= 0.0 { (1.0, 0.0) } else { (r + (1.0 - r).powi(2) * r * a * a / denominator, (1.0 - r).powi(2) * a / denominator) }
+ };
+ let s = series(f.s);
+ let p = series(f.p);
+ reflection[channel] = (s.0 + p.0) * 0.5;
+ transmission[channel] = (s.1 + p.1) * 0.5;
+ }
+ Ok((
+ Interface { transmitted: Some(direction), ..optics },
+ Vec3::new(reflection[0], reflection[1], reflection[2]),
+ Vec3::new(transmission[0], transmission[1], transmission[2]),
+ ))
+}
+
pub fn attenuation(sigma: [f64; 3], distance_mm: f64) -> Result<Vec3> {
if !distance_mm.is_finite()
|| !(0.0..=super::MAX_DISTANCE_MM).contains(&distance_mm)
diff --git a/crates/render/src/raytrace/dielectric_tests.rs b/crates/render/src/raytrace/dielectric_tests.rs
index 2a1ed3e863..b0eed8d458 100644
--- a/crates/render/src/raytrace/dielectric_tests.rs
+++ b/crates/render/src/raytrace/dielectric_tests.rs
@@ -28,6 +28,7 @@ pub(in crate::raytrace) fn scene(body: ProductMesh) -> ProductScene {
}
pub(in crate::raytrace) fn input(boundary: DielectricBoundary) -> DielectricOptions {
DielectricOptions {
+ model: None,
shadow_transmission: false,
subsurface: None,
body_index: 0,
@@ -1069,3 +1070,116 @@ fn general_box_axis_planes_undo_only_single_ulp_padding_and_keep_raw_zero_endpoi
assert!(captured.meshes[0].mesh.positions.iter().filter(|point| point.z == 0.0).all(|point| point.z.to_bits() == bits));
}
}
+
+// Independent unit-square cell tilings: duplicate vertex indices deliberately
+// retain exact coordinates so certification cannot assume indexed welding.
+fn tiled_path_sheet(cells: &[(i32, i32)]) -> ProductMesh {
+ let mut body = box_body(1.0);
+ let mut mesh = Mesh::default();
+ for &(x, y) in cells {
+ let (x, y) = (f64::from(x), f64::from(y));
+ let begin = mesh.positions.len() as u32;
+ mesh.positions.extend([Vec3::new(x, y, 0.0), Vec3::new(x + 1.0, y, 0.0), Vec3::new(x + 1.0, y + 1.0, 0.0), Vec3::new(x, y + 1.0, 0.0)]);
+ mesh.triangles.extend([[begin, begin + 1, begin + 2], [begin, begin + 2, begin + 3]]);
+ }
+ body.mesh = Arc::new(mesh);
+ body
+}
+fn path_sheet_options() -> RaytraceOptions {
+ let mut options = general_options();
+ options.dielectrics[0].boundary = DielectricBoundary::ThinSheet;
+ options.dielectrics[0].thickness_mm = 0.7;
+ options
+}
+#[test]
+fn general_path_sheets_accept_exact_tilings_concavity_holes_and_either_global_winding() {
+ let rectangle = [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)];
+ let concave = [(0, 0), (1, 0), (0, 1)];
+ let ring = [(0, 0), (1, 0), (2, 0), (0, 1), (2, 1), (0, 2), (1, 2), (2, 2)];
+ let options = path_sheet_options();
+ for cells in [&rectangle[..], &concave[..], &ring[..]] {
+ for reverse in [false, true] {
+ let mut body = tiled_path_sheet(cells);
+ let mesh = Arc::make_mut(&mut body.mesh);
+ for p in &mut mesh.positions {
+ // Integer oblique plane: exact coplanarity does not depend on a
+ // normalized floating normal or on alignment with a world axis.
+ p.z = p.x + p.y;
+ if p.x == 0.0 {
+ p.x = -0.0;
+ }
+ }
+ if reverse {
+ for triangle in &mut mesh.triangles {
+ triangle.swap(1, 2);
+ }
+ }
+ let expected = mesh.triangles.len();
+ let captured = scene(body.clone());
+ let proof = general_certificate(&captured, &options).unwrap();
+ let region = proof.region(0).unwrap();
+ assert_eq!(region.primitive_end - region.primitive_begin, expected);
+ assert_eq!(region.parent, None);
+ assert!(certify(&captured, &input(DielectricBoundary::ThinSheet)).is_err(), "legacy optics retain their original two-triangle domain");
+ }
+ }
+}
+#[test]
+fn general_path_sheets_refuse_folded_disconnected_overlapping_and_ambiguous_tilings() {
+ let cells = [(0, 0), (1, 0), (0, 1), (1, 1)];
+ let options = path_sheet_options();
+ let mut cases = vec![tiled_path_sheet(&[]), tiled_path_sheet(&[(0, 0), (2, 0)]), tiled_path_sheet(&[(0, 0), (1, 1)])];
+ let mut folded = tiled_path_sheet(&cells);
+ Arc::make_mut(&mut folded.mesh).positions[0].z = 0.125;
+ cases.push(folded);
+ let mut reversed = tiled_path_sheet(&cells);
+ Arc::make_mut(&mut reversed.mesh).triangles[2].swap(1, 2);
+ cases.push(reversed);
+ let mut duplicated = tiled_path_sheet(&cells);
+ let duplicate = duplicated.mesh.triangles[0];
+ Arc::make_mut(&mut duplicated.mesh).triangles.push(duplicate);
+ cases.push(duplicated);
+ let mut overlap = tiled_path_sheet(&cells);
+ let mesh = Arc::make_mut(&mut overlap.mesh);
+ let begin = mesh.positions.len() as u32;
+ mesh.positions.extend([Vec3::new(0.25, 0.25, 0.0), Vec3::new(1.5, 0.25, 0.0), Vec3::new(0.25, 1.5, 0.0)]);
+ mesh.triangles.push([begin, begin + 1, begin + 2]);
+ cases.push(overlap);
+ // One cell ends with a complete edge, the adjacent cell has a vertex in its
+ // interior. Geometric coincidence is never used to repair that T-junction.
+ let mut junction = tiled_path_sheet(&[(0, 0)]);
+ let mesh = Arc::make_mut(&mut junction.mesh);
+ mesh.positions.extend([Vec3::new(1.0, 0.5, 0.0), Vec3::new(2.0, 0.0, 0.0), Vec3::new(2.0, 1.0, 0.0)]);
+ mesh.triangles.extend([[1, 5, 4], [4, 5, 6], [4, 6, 2]]);
+ cases.push(junction);
+ for body in cases {
+ assert!(general_certificate(&scene(body), &options).is_err(), "a valid sheet needs exact topology and nonoverlapping planar triangles");
+ }
+}
+#[test]
+fn general_path_sheet_preparation_is_prepaid_charged_and_cancellable_without_a_partial_proof() {
+ let cells = [(0, 0), (1, 0), (2, 0), (0, 1), (2, 1), (0, 2), (1, 2), (2, 2)];
+ let captured = scene(tiled_path_sheet(&cells));
+ let options = path_sheet_options();
+ let charged = super::super::glass_mesh::Task::required_bytes(&captured, &options).unwrap();
+ let empty = RaytraceOptions { dielectrics: Vec::new(), ..options.clone() };
+ let fixed = super::super::glass_mesh::Task::required_bytes(&captured, &empty).unwrap();
+ assert!(charged > fixed, "sheet faces and edge/link scratch are included in exact admission");
+ for prefix in [1, 17, 61, 127, 509] {
+ let cancel = CancelToken::default();
+ let mut task = super::super::glass_mesh::Task::new(&captured, &options).unwrap();
+ let mut work = super::super::WorkBudget::new(prefix).unwrap();
+ for _ in 0..prefix {
+ let before = work.used();
+ task.step(&captured, &options, &mut work, &cancel).unwrap();
+ assert_eq!(work.used(), before + 1);
+ assert!(!task.ready());
+ }
+ assert_eq!(task.step(&captured, &options, &mut work, &cancel).unwrap_err().code, job::ErrorCode::LimitExceeded);
+ assert!(!task.ready());
+ assert!(task.region(0).is_err());
+ cancel.cancel();
+ assert_eq!(task.step(&captured, &options, &mut work, &cancel).unwrap_err().code, job::ErrorCode::Cancelled);
+ assert!(!task.ready());
+ }
+}
diff --git a/crates/render/src/raytrace/glass_mesh.rs b/crates/render/src/raytrace/glass_mesh.rs
index 941fc55f36..a32be653fc 100644
--- a/crates/render/src/raytrace/glass_mesh.rs
+++ b/crates/render/src/raytrace/glass_mesh.rs
@@ -1,7 +1,8 @@
//! Cooperative certification of the exact f64 boundary consumed by CPU Path.
//! Coordinates are never tolerance-welded, snapped or repaired. Every shared edge must have
-//! identical finite endpoints (ClosedMesh canonicalises signed zero; declared boxes
-//! retain the legacy raw-bit edge policy); geometric contact is
+//! identical finite endpoints (ClosedMesh and sheets canonicalise signed zero; declared
+//! boxes retain the legacy raw-bit edge policy). Sheets may have manifold boundary
+//! edges, concavity and holes; geometric contact is
//! permitted only along the same body's actual shared topological simplex.
use super::{Bounds, Triangle, WorkBudget};
use crate::{
@@ -229,9 +230,7 @@ fn selected_count(scene: &ProductScene, options: &RaytraceOptions) -> job::Resul
let mut count = 0_usize;
for input in &options.dielectrics {
let body = scene.meshes.get(input.body_index).filter(|b| b.name == input.body_name).ok_or_else(|| invalid("CPU glass target changed"))?;
- if input.boundary != DielectricBoundary::ThinSheet {
- count = count.checked_add(body.mesh.triangles.len()).ok_or_else(memory)?;
- }
+ count = count.checked_add(body.mesh.triangles.len()).ok_or_else(memory)?;
}
if count as u64 > options.budget.limits().max_triangles {
return Err(memory());
@@ -327,9 +326,8 @@ impl Task {
region.primitive_begin = self.i;
region.primitive_end = self.i.checked_add(body.mesh.triangles.len()).ok_or_else(memory)?;
match input.boundary {
- DielectricBoundary::ThinSheet => {
- super::dielectric::certify_sheet(&body.mesh).map_err(super::image::error)?;
- }
+ // Path sheets use this task's charged planar/manifold proof.
+ DielectricBoundary::ThinSheet => {}
DielectricBoundary::ClosedBox => {
if !(12..=super::dielectric::MAX_BOX_TRIANGLES).contains(&body.mesh.triangles.len()) {
return Err(invalid("unsupported dielectric boundary tessellation"));
@@ -365,8 +363,8 @@ impl Task {
}
let Some(indices) = body.mesh.triangles.get(self.triangle) else {
region.end = self.faces.len();
- if input.boundary != DielectricBoundary::ThinSheet && region.end == region.begin {
- return Err(invalid("closed CPU glass has no triangles"));
+ if region.end == region.begin {
+ return Err(invalid("CPU glass boundary has no triangles"));
}
self.medium += 1;
self.triangle = 0;
@@ -381,14 +379,26 @@ impl Task {
return Err(invalid("CPU glass boundary contains a degenerate triangle"));
}
region.bounds = region.bounds.include(Triangle::new(p).map_err(super::image::error)?.bounds());
- if input.boundary != DielectricBoundary::ThinSheet {
- if self.faces.len() == self.faces.capacity() {
- return Err(memory());
+ if input.boundary == DielectricBoundary::ThinSheet
+ && let Some(first) = self.faces.get(region.begin)
+ {
+ if !same_plane(first.p, p) {
+ return Err(invalid("CPU thin sheet must have one exact planar boundary"));
}
- self.parents.push(self.faces.len());
- self.ranks.push(0);
- self.faces.push(Face { p, medium: self.medium });
+ let drop = projection(first.p);
+ let a = first.p.map(|p| project(p, drop));
+ let b = p.map(|p| project(p, drop));
+ let winding = orient2d(b[0], b[1], b[2]);
+ if winding == 0.0 || opposite(orient2d(a[0], a[1], a[2]), winding) {
+ return Err(invalid("CPU thin sheet triangles must have consistent winding"));
+ }
+ }
+ if self.faces.len() == self.faces.capacity() {
+ return Err(memory());
}
+ self.parents.push(self.faces.len());
+ self.ranks.push(0);
+ self.faces.push(Face { p, medium: self.medium });
self.triangle += 1;
}
Stage::BoxAxes => {
@@ -487,10 +497,16 @@ impl Task {
self.i = 0;
return Ok(());
};
- let b = *self.edges.get(self.i + 1).ok_or_else(|| invalid("CPU glass requires closed edges"))?;
let group = |x: Edge| (x.medium, x.a, x.b);
- if group(a) != group(b) || a.forward == b.forward || self.edges.get(self.i + 2).is_some_and(|x| group(*x) == group(a)) {
- return Err(invalid("CPU glass requires exactly two oppositely wound faces per edge"));
+ let Some(b) = self.edges.get(self.i + 1).copied().filter(|b| group(a) == group(*b)) else {
+ if options.dielectrics.get(a.medium).is_some_and(|input| input.boundary == DielectricBoundary::ThinSheet) {
+ self.i += 1;
+ return Ok(());
+ }
+ return Err(invalid("CPU glass requires closed edges"));
+ };
+ if a.forward == b.forward || self.edges.get(self.i + 2).is_some_and(|x| group(*x) == group(a)) {
+ return Err(invalid("CPU glass requires at most two oppositely wound faces per edge; closed boundaries require exactly two"));
}
let ra = self.root(a.face)?;
let rb = self.root(b.face)?;
@@ -501,7 +517,7 @@ impl Task {
if let Some(face) = self.faces.get(self.i) {
let region = self.regions.get(face.medium).ok_or_else(|| invalid("CPU glass region missing"))?;
if self.root(self.i)? != self.root(region.begin)? {
- return Err(invalid("each CPU closed glass body must contain one connected shell"));
+ return Err(invalid("each CPU glass body must contain one edge-connected boundary"));
}
self.i += 1;
} else {
@@ -535,7 +551,13 @@ impl Task {
self.i = 0;
return Ok(());
};
- let b = *self.edges.get(self.i + 1).ok_or_else(|| invalid("CPU glass corner edge pair"))?;
+ let Some(b) = self.edges.get(self.i + 1).copied().filter(|b| (a.medium, a.a, a.b) == (b.medium, b.a, b.b)) else {
+ // Sheet boundary edges have one face and do not join two
+ // corner records. Closed-edge completeness was proved above.
+ self.i += 1;
+ self.vertex = 0;
+ return Ok(());
+ };
let coordinate = if self.vertex == 0 { a.a } else { a.b };
let corner = |edge: Edge| -> job::Result<usize> {
let face = self.faces.get(edge.face).ok_or_else(|| invalid("CPU glass corner face"))?;
@@ -582,7 +604,9 @@ impl Task {
&& (a.medium, a.a) == (b.medium, b.a)
&& self.root(a.face)? != self.root(b.face)?
{
- return Err(invalid("CPU glass vertex link must be one connected cycle; pinched or touching fans are unsupported"));
+ return Err(invalid(
+ "CPU glass vertex link must be one connected cycle or sheet boundary path; pinched or touching fans are unsupported",
+ ));
}
self.i += 1;
}
diff --git a/crates/render/src/raytrace/image.rs b/crates/render/src/raytrace/image.rs
index b70998dbc4..df9078a84b 100644
--- a/crates/render/src/raytrace/image.rs
+++ b/crates/render/src/raytrace/image.rs
@@ -369,6 +369,7 @@ pub(crate) fn admit_layout(scene: &ProductScene, request: &ImageRequest, options
} else {
0
};
+ let caustics_bytes = options.caustics.map_or(Ok(0), caustics::Task::required_bytes)?;
let extra = BvhBuilder::required_bytes(n, n, limits(options.budget))
.map_err(error)?
.checked_add(a.triangles.checked_mul(std::mem::size_of::<Look>() as u64).ok_or_else(|| error(TraceError::MemoryLimit))?)
@@ -378,6 +379,7 @@ pub(crate) fn admit_layout(scene: &ProductScene, request: &ImageRequest, options
.and_then(|v| v.checked_add(aging_bytes))
.and_then(|v| v.checked_add(optical_bytes))
.and_then(|v| v.checked_add(general_glass_bytes))
+ .and_then(|v| v.checked_add(caustics_bytes))
.and_then(|v| v.checked_add(if options.path.is_some() { std::mem::size_of::<indirect_image::State>() as u64 } else { 0 }))
.and_then(|v| v.checked_add(film_bytes))
.and_then(|v| v.checked_add(adaptive_bytes))
@@ -597,6 +599,8 @@ fn resume_optical_path(pending: &mut PendingPixel, path: OpticalPath) {
pending.environment_value = Vec3::ZERO;
}
+#[path = "image_caustics.rs"]
+mod caustics;
#[path = "image_indirect.rs"]
mod indirect_image;
@@ -604,6 +608,7 @@ pub struct ImageTask {
maps: Vec<job::textures::cpu_cache::CpuTextureCache>,
aging: Vec<super::aging::Task>,
path: Vec<indirect_image::State>,
+ caustics: Vec<caustics::Task>,
punctual_diagnostics: job::PunctualDiagnostics,
progressive: Option<Progressive>,
sampling: Vec<job::adaptive::SamplingReport>,
@@ -866,10 +871,19 @@ impl ImageTask {
Ok(Progressive { film, options, target, resolving: false, resolve_pixel: 0 })
})
.transpose()?;
+ let mut caustics = Vec::new();
+ if let Some(options) = options.caustics {
+ caustics.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?;
+ if caustics.capacity() != 1 {
+ return Err(error(TraceError::MemoryLimit));
+ }
+ caustics.push(caustics::Task::new(options)?);
+ }
Ok(Self {
maps,
aging,
path,
+ caustics,
punctual_diagnostics: Default::default(),
progressive,
sampling,
@@ -929,6 +943,9 @@ impl ImageTask {
(Phase::Preparing, done, total)
} else if self.glass.first().is_some_and(|glass| !glass.ready()) {
(Phase::Preparing, 0, 1)
+ } else if self.bvh.is_some() && self.caustics.first().is_some_and(|map| !map.ready()) {
+ let (done, total) = self.caustics.first().map_or((0, 1), caustics::Task::progress);
+ (Phase::Preparing, done, total)
} else if self.bvh.is_some() && self.denoise.first().is_some_and(|guides| !guides.ready()) {
(
Phase::Preparing,
@@ -1913,6 +1930,7 @@ impl ImageTask {
self.options.volume = None;
self.pending.release();
self.path = Vec::new();
+ self.caustics = Vec::new();
self.request.raytrace = None;
self.options.lights = None;
self.options.emissions = None;
@@ -2069,6 +2087,8 @@ impl ImageTask {
.ok_or_else(|| invalid("missing environment preparation"))?
.prepare_one(|| self.cancel.is_cancelled())
.map_err(environment_error)?;
+ } else if self.bvh.is_some() && self.caustics.first().is_some_and(|map| !map.ready()) {
+ caustics::step(self)?;
} else if self.bvh.is_some() && self.denoise.first().is_some_and(|guides| !guides.ready()) {
let bvh = self.bvh.as_ref().ok_or_else(|| invalid("missing CPU guide BVH"))?;
self.denoise.first_mut().ok_or_else(|| invalid("missing CPU guide task"))?.step(
diff --git a/crates/render/src/raytrace/image_caustics.rs b/crates/render/src/raytrace/image_caustics.rs
new file mode 100644
index 0000000000..86343bd650
--- /dev/null
+++ b/crates/render/src/raytrace/image_caustics.rs
@@ -0,0 +1,816 @@
+//! Opt-in, bounded delta-source photon density estimate. Every trace, event,
+//! merge-sort copy, grid lookup and gathered photon cooperates with the job ledger.
+use super::*;
+use crate::glass_model::WAVELENGTHS_NM;
+use std::f64::consts::{PI, TAU};
+
+#[derive(Clone, Copy, Default)]
+struct Photon {
+ cell: [i64; 3],
+ position: Vec3,
+ normal: Vec3,
+ incoming: Vec3,
+ flux: Vec3,
+ body: usize,
+ kind: ReceiverKind,
+ side: i8,
+ source: u32,
+}
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+enum ReceiverKind {
+ #[default]
+ Opaque,
+ Rough,
+ Volume,
+}
+#[derive(Clone, Copy)]
+struct Sheet {
+ index: usize,
+ normal: Vec3,
+ geometric: Vec3,
+ direction: Vec3,
+ ray: Ray,
+ hit: super::super::Hit,
+}
+struct Path {
+ ray: Ray,
+ cursor: Option<TraceCursor>,
+ hit: Option<super::super::Hit>,
+ emitter: Option<(usize, f64, Vec3)>,
+ emitter_cursor: usize,
+ flux: Vec3,
+ from: Vec3,
+ media: [usize; 8],
+ len: usize,
+ depth: u8,
+ optical: bool,
+ channel: Option<u8>,
+ source: Option<(Vec3, f64)>,
+ source_index: u32,
+ source_plane: Option<[Vec3; 3]>,
+ sheet: Option<Sheet>,
+ origin: Option<super::super::origin::Task>,
+ verify_origin: bool,
+ reservoir: Option<Photon>,
+ candidates: u8,
+}
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Stage {
+ Emit,
+ Origin,
+ Trace,
+ Emitters,
+ Resolve,
+ Sheet,
+ Sort,
+ Ready,
+}
+pub(super) struct Task {
+ photons: Vec<Photon>,
+ scratch: Vec<Photon>,
+ options: job::CausticOptions,
+ ordinal: u32,
+ path: Option<Path>,
+ stage: Stage,
+ width: usize,
+ begin: usize,
+ left: usize,
+ right: usize,
+ end: usize,
+ out: usize,
+}
+fn model_error(error: impl std::fmt::Display) -> JobError {
+ JobError::new(ErrorCode::InvalidScene, error.to_string())
+}
+fn finite_flux(flux: Vec3) -> job::Result<()> {
+ if !flux.is_finite() || flux.x < 0.0 || flux.y < 0.0 || flux.z < 0.0 {
+ return Err(invalid("CPU caustic photon power is nonfinite or negative"));
+ }
+ Ok(())
+}
+fn cell(position: Vec3, radius: f64) -> job::Result<[i64; 3]> {
+ let values = [position.x, position.y, position.z].map(|value| (value / radius).floor());
+ if values.iter().any(|value| !value.is_finite() || value.abs() > 4e18) {
+ return Err(invalid("CPU caustic spatial cell exceeds its bounded integer domain"));
+ }
+ Ok(values.map(|value| value as i64))
+}
+fn reserve<T>(count: usize) -> job::Result<Vec<T>> {
+ let mut values = Vec::new();
+ values.try_reserve_exact(count).map_err(|_| error(TraceError::AllocationFailed))?;
+ if values.capacity() != count {
+ return Err(error(TraceError::MemoryLimit));
+ }
+ Ok(values)
+}
+impl Task {
+ pub(super) fn required_bytes(options: job::CausticOptions) -> job::Result<u64> {
+ options.validate()?;
+ u64::from(options.photons)
+ .checked_mul(2 * std::mem::size_of::<Photon>() as u64)
+ .and_then(|bytes| bytes.checked_add(std::mem::size_of::<Self>() as u64))
+ .ok_or_else(|| error(TraceError::MemoryLimit))
+ }
+ pub(super) fn new(options: job::CausticOptions) -> job::Result<Self> {
+ Self::required_bytes(options)?;
+ Ok(Self {
+ photons: reserve(options.photons as usize)?,
+ scratch: reserve(options.photons as usize)?,
+ options,
+ ordinal: 0,
+ path: None,
+ stage: Stage::Emit,
+ width: 1,
+ begin: 0,
+ left: 0,
+ right: 0,
+ end: 0,
+ out: 0,
+ })
+ }
+ pub(super) fn ready(&self) -> bool {
+ self.stage == Stage::Ready
+ }
+ #[cfg(test)]
+ pub(super) fn receiver_counts(&self) -> [usize; 3] {
+ let mut counts = [0; 3];
+ for photon in &self.photons {
+ counts[match photon.kind {
+ ReceiverKind::Opaque => 0,
+ ReceiverKind::Rough => 1,
+ ReceiverKind::Volume => 2,
+ }] += 1;
+ }
+ counts
+ }
+ pub(super) fn progress(&self) -> (u64, u64) {
+ (u64::from(self.ordinal), u64::from(self.options.photons))
+ }
+ fn random(&self, depth: u8, domain: u64) -> [f64; 2] {
+ super::super::progressive::variates(self.options.seed, 0, self.ordinal, 0x4341_5553_0000 + u64::from(depth) * 256 + domain)
+ }
+ fn finish_path(&mut self) -> job::Result<()> {
+ if let Some(path) = self.path.take()
+ && let Some(mut photon) = path.reservoir
+ {
+ photon.flux = photon.flux * f64::from(path.candidates);
+ finite_flux(photon.flux)?;
+ if self.photons.len() == self.photons.capacity() || self.scratch.len() == self.scratch.capacity() {
+ return Err(error(TraceError::MemoryLimit));
+ }
+ self.photons.push(photon);
+ self.scratch.push(Photon::default());
+ }
+ self.ordinal += 1;
+ self.stage = Stage::Emit;
+ Ok(())
+ }
+}
+fn candidate(
+ map: &Task,
+ position: Vec3,
+ normal: Vec3,
+ incoming: Vec3,
+ body: usize,
+ kind: ReceiverKind,
+ side: i8,
+ path: &mut Path,
+) -> job::Result<()> {
+ if !path.optical || path.flux == Vec3::ZERO || path.source.is_some_and(|(origin, minimum)| origin.dist(position) < minimum) {
+ return Ok(());
+ }
+ path.candidates = path
+ .candidates
+ .checked_add(1)
+ .filter(|count| *count <= map.options.max_depth)
+ .ok_or_else(|| invalid("CPU caustic receiver reservoir exceeds its path depth"))?;
+ // One independent counter draw selects a uniform visit, without changing
+ // any interface, wavelength, or free-flight variate on this light path.
+ if map.random(path.depth, 13)[0] < 1.0 / f64::from(path.candidates) {
+ path.reservoir = Some(Photon {
+ cell: cell(position, map.options.radius_mm)?,
+ position,
+ normal,
+ incoming,
+ flux: path.flux,
+ body,
+ kind,
+ side,
+ source: path.source_index,
+ });
+ }
+ Ok(())
+}
+fn prepared(task: &ImageTask) -> job::Result<PreparedScene<'_>> {
+ Ok(PreparedScene { bvh: task.bvh.as_ref().ok_or_else(|| invalid("CPU caustic BVH missing"))?, primitives: &task.looks, source: &task.scene })
+}
+fn normal_basis(n: Vec3, x: f64, y: f64, z: f64) -> job::Result<Vec3> {
+ let tangent =
+ super::super::unit((if n.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z }).cross(n)).ok_or_else(|| invalid("CPU caustic source basis"))?;
+ super::super::unit(tangent * x + n.cross(tangent) * y + n * z).ok_or_else(|| invalid("CPU caustic source direction"))
+}
+fn emit(map: &mut Task, task: &ImageTask) -> job::Result<()> {
+ let punctual = task.options.punctual_lights.as_ref().map_or(0, Vec::len);
+ let count = task.lights.lights().len() + punctual;
+ if map.ordinal == map.options.photons || count == 0 || task.scene.meshes.is_empty() {
+ map.stage = Stage::Sort;
+ return Ok(());
+ }
+ let source = (map.random(0, 0)[0] * count as f64) as usize;
+ let [u, v] = map.random(0, 1);
+ let normalization = count as f64 / f64::from(map.options.photons);
+ let (origin, direction, flux, point_source) = if let Some(light) = task.lights.lights().get(source) {
+ let bounds = task.scene.bounds;
+ let center = bounds.min * 0.5 + bounds.max * 0.5;
+ let radius = (bounds.max - bounds.min).len() * 0.5;
+ if !center.is_finite() || !radius.is_finite() || radius <= 0.0 {
+ map.finish_path()?;
+ return Ok(());
+ }
+ let r = radius * u.sqrt();
+ let phi = TAU * v;
+ let disk = normal_basis(light.direction(), phi.cos(), phi.sin(), 0.0)?;
+ // normal_basis normalizes; retain the actual uniform-disk radius.
+ let origin = center + light.direction() * (radius + 1.0) + disk * r;
+ (origin, -light.direction(), light.color() * (light.intensity() * PI * radius * radius * normalization), None)
+ } else {
+ let light = task
+ .options
+ .punctual_lights
+ .as_ref()
+ .and_then(|lights| lights.get(source - task.lights.lights().len()))
+ .ok_or_else(|| invalid("CPU caustic point source index"))?;
+ let origin = Vec3::new(light.position_mm[0], light.position_mm[1], light.position_mm[2]);
+ let (direction, density, cone) = if let Some(cone) = light.cone {
+ let axis = super::super::unit(Vec3::new(cone.emitted_axis[0], cone.emitted_axis[1], cone.emitted_axis[2]))
+ .ok_or_else(|| invalid("CPU caustic cone axis"))?;
+ let outer = cone.outer_half_angle_radians.cos();
+ let inner = cone.inner_half_angle_radians.cos();
+ let cosine = 1.0 - u * (1.0 - outer);
+ let sine = (1.0 - cosine * cosine).max(0.0).sqrt();
+ let direction = normal_basis(axis, sine * (TAU * v).cos(), sine * (TAU * v).sin(), cosine)?;
+ let feather = ((cosine - outer) / (inner - outer)).clamp(0.0, 1.0);
+ (direction, 1.0 / (TAU * (1.0 - outer)), feather * feather * (3.0 - 2.0 * feather))
+ } else {
+ let z = 1.0 - 2.0 * u;
+ let sine = (1.0 - z * z).max(0.0).sqrt();
+ (Vec3::new(sine * (TAU * v).cos(), sine * (TAU * v).sin(), z), 1.0 / (4.0 * PI), 1.0)
+ };
+ let color = Vec3::new(light.color[0], light.color[1], light.color[2]);
+ (
+ origin,
+ direction,
+ color * (light.intensity * light.reference_distance_mm.powi(2) * cone * normalization / density),
+ Some((origin, light.minimum_distance_mm)),
+ )
+ };
+ finite_flux(flux)?;
+ if flux == Vec3::ZERO {
+ map.finish_path()?;
+ return Ok(());
+ }
+ let ray = Ray::new(origin, direction, 0.0_f64.next_up(), super::super::MAX_DISTANCE_MM).map_err(error)?;
+ let origin_task = if let Some(certificate) = task.glass.first() {
+ super::super::origin::Task::required(certificate, &task.options.dielectrics, origin, origin)?
+ .then(|| super::super::origin::Task::new(origin, origin))
+ .transpose()?
+ } else {
+ None
+ };
+ map.stage = if origin_task.is_some() { Stage::Origin } else { Stage::Trace };
+ map.path = Some(Path {
+ ray,
+ cursor: Some(TraceCursor::new(ray, false)),
+ hit: None,
+ emitter: None,
+ emitter_cursor: 0,
+ flux,
+ from: origin,
+ media: [0; 8],
+ len: 0,
+ depth: 0,
+ optical: false,
+ channel: None,
+ source: point_source,
+ source_index: if source < task.lights.lights().len() {
+ u32::MAX
+ } else {
+ u32::try_from(source - task.lights.lights().len()).map_err(|_| invalid("CPU caustic source index exceeds its bounded record"))?
+ },
+ source_plane: None,
+ sheet: None,
+ origin: origin_task,
+ verify_origin: false,
+ reservoir: None,
+ candidates: 0,
+ });
+ Ok(())
+}
+fn current(path: &Path) -> job::Result<Option<usize>> {
+ if path.len == 0 { Ok(None) } else { path.media.get(path.len - 1).copied().map(Some).ok_or_else(|| invalid("CPU caustic medium stack index")) }
+}
+fn wavelength(path: &Path) -> job::Result<f64> {
+ WAVELENGTHS_NM.get(usize::from(path.channel.unwrap_or(1))).copied().ok_or_else(|| invalid("CPU caustic wavelength channel"))
+}
+fn ior(task: &ImageTask, path: &Path, index: Option<usize>) -> job::Result<f64> {
+ let Some(index) = index else { return Ok(1.0) };
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU caustic medium disappeared"))?;
+ input.model.unwrap_or_default().ior(input.ior, wavelength(path)?).map_err(model_error)
+}
+fn select_spectrum(map: &Task, task: &ImageTask, path: &mut Path, index: usize) -> job::Result<()> {
+ if path.channel.is_some() {
+ return Ok(());
+ }
+ let spectral = |index: usize| task.options.dielectrics.get(index).and_then(|input| input.model).is_some_and(|model| model.spectral());
+ if !spectral(index) && !current(path)?.is_some_and(spectral) {
+ return Ok(());
+ }
+ let channel = (map.random(path.depth, 7)[0] * 3.0) as u8;
+ path.flux = multiply(
+ path.flux,
+ match channel {
+ 0 => Vec3::new(3.0, 0.0, 0.0),
+ 1 => Vec3::new(0.0, 3.0, 0.0),
+ 2 => Vec3::new(0.0, 0.0, 3.0),
+ _ => return Err(invalid("CPU caustic wavelength draw")),
+ },
+ );
+ path.channel = Some(channel);
+ Ok(())
+}
+fn launch(task: &ImageTask, path: &mut Path, index: usize, hit: SharedHit<'_>, direction: Vec3) -> job::Result<()> {
+ let region = task.glass.first().ok_or_else(|| invalid("CPU caustic glass certificate missing"))?.region(index)?;
+ let ray = Ray::new(hit.position, direction, 0.0_f64.next_up(), super::super::MAX_DISTANCE_MM).map_err(error)?;
+ path.ray = ray;
+ path.cursor = Some(TraceCursor::from_plane(ray, region.primitive_begin..region.primitive_end, hit.vertices));
+ path.hit = None;
+ path.emitter = None;
+ path.emitter_cursor = 0;
+ path.from = hit.position;
+ path.source_plane = Some(hit.vertices);
+ path.depth += 1;
+ Ok(())
+}
+fn sample_uniforms(map: &Task, path: &Path) -> [f64; 3] {
+ let [branch, x] = map.random(path.depth, 2);
+ let [y, _] = map.random(path.depth, 3);
+ [x, y, branch]
+}
+fn smooth_sheet(input: &job::DielectricOptions, path: &Path, normal: Vec3) -> job::Result<(Vec3, Vec3)> {
+ let (_, r, t) = dielectric::modeled_sheet(path.ray.direction(), normal, input).map_err(error)?;
+ Ok((r, t))
+}
+
+fn resolve(map: &mut Task, task: &ImageTask, path: &mut Path) -> job::Result<bool> {
+ let geometry = path.hit.map(|hit| prepared(task)?.resolve_hit(path.ray, hit).map_err(error)).transpose()?;
+ let emitter = path.emitter.filter(|(_, distance, _)| geometry.as_ref().is_none_or(|hit| *distance < hit.distance_mm));
+ let endpoint = if let Some((_, _, position)) = emitter {
+ position
+ } else if let Some(hit) = &geometry {
+ hit.position
+ } else {
+ if path.len != 0 {
+ return Err(invalid("CPU caustic photon escaped its certified closed medium"));
+ }
+ return Ok(true);
+ };
+ let distance = path.from.dist(endpoint);
+ if let Some(index) = current(path)? {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU caustic absorbing medium missing"))?;
+ if let Some(scattering) = input.subsurface.filter(|scattering| scattering.active()) {
+ let travel = scattering.free_flight(map.random(path.depth, 8)[0]).map_err(model_error)?;
+ if travel < distance {
+ let position = path.from + path.ray.direction() * travel;
+ if position == path.from || position == endpoint {
+ return Err(invalid("CPU caustic scattering collision is not representable"));
+ }
+ for plane in [path.source_plane, geometry.as_ref().filter(|_| emitter.is_none()).map(|hit| hit.vertices)].into_iter().flatten() {
+ if super::super::glass_mesh::origin_on_plane(plane, position)? {
+ return Err(invalid("CPU caustic scattering collision rounds onto an interface"));
+ }
+ }
+ if let Some((index, _, _)) = emitter {
+ let light = task
+ .options
+ .area_lights
+ .as_ref()
+ .and_then(|lights| lights.get(index))
+ .ok_or_else(|| invalid("CPU caustic analytic emitter missing"))?;
+ if super::super::indirect::Rectangle::new(light).map_err(error)?.on_plane(position) {
+ return Err(invalid("CPU caustic collision rounds onto an analytic emitter plane"));
+ }
+ }
+ path.flux = multiply(path.flux, dielectric::attenuation(input.absorption_per_mm, travel).map_err(error)?);
+ candidate(map, position, Vec3::ZERO, -path.ray.direction(), input.body_index, ReceiverKind::Volume, 0, path)?;
+ if path.depth + 1 >= map.options.max_depth {
+ return Ok(true);
+ }
+ let direction = scattering.sample_direction(path.ray.direction(), map.random(path.depth, 9)).map_err(model_error)?;
+ path.ray = Ray::new(position, direction, 0.0_f64.next_up(), super::super::MAX_DISTANCE_MM).map_err(error)?;
+ path.from = position;
+ path.cursor = Some(TraceCursor::new(path.ray, false));
+ path.hit = None;
+ path.emitter = None;
+ path.emitter_cursor = 0;
+ path.source_plane = None;
+ path.depth += 1;
+ path.optical = true;
+ path.origin = Some(super::super::origin::Task::new(position, position)?);
+ path.verify_origin = true;
+ map.stage = Stage::Origin;
+ return Ok(false);
+ }
+ }
+ path.flux = multiply(path.flux, dielectric::attenuation(input.absorption_per_mm, distance).map_err(error)?);
+ }
+ if emitter.is_some() {
+ return Ok(true);
+ }
+ let hit = geometry.ok_or_else(|| invalid("CPU caustic geometric endpoint disappeared"))?;
+ let raw = path.hit.ok_or_else(|| invalid("CPU caustic raw endpoint disappeared"))?;
+ let selected = task.options.dielectrics.iter().position(|input| input.body_index == hit.body_index && input.body_name == hit.body_name);
+ let Some(index) = selected else {
+ candidate(map, hit.position, hit.oriented_geometric_normal(), -path.ray.direction(), hit.body_index, ReceiverKind::Opaque, 0, path)?;
+ return Ok(true);
+ };
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU caustic optical material missing"))?;
+ let model = input.model.unwrap_or_default();
+ let thin = input.boundary == job::DielectricBoundary::ThinSheet;
+ if model.roughness > 0.0 {
+ let side = if thin { if hit.front_face { 1 } else { -1 } } else { 0 };
+ candidate(map, hit.position, hit.geometric_normal, -path.ray.direction(), hit.body_index, ReceiverKind::Rough, side, path)?;
+ }
+ if path.depth + 1 >= map.options.max_depth {
+ return Ok(true);
+ }
+ if !thin || model.roughness > 0.0 {
+ select_spectrum(map, task, path, index)?;
+ }
+ let medium = current(path)?;
+ let region = task.glass.first().ok_or_else(|| invalid("CPU caustic glass certificate missing"))?.region(index)?;
+ let next = if thin {
+ if medium.is_some() {
+ return Err(invalid("CPU caustic sheet lies inside a closed medium"));
+ }
+ Some(index)
+ } else if hit.front_face {
+ if medium != region.parent {
+ return Err(invalid("CPU caustic entry disagrees with its certified parent"));
+ }
+ Some(index)
+ } else {
+ if medium != Some(index) {
+ return Err(invalid("CPU caustic exit disagrees with the current medium"));
+ }
+ region.parent
+ };
+ let ni = ior(task, path, medium)?;
+ let nt = ior(task, path, next)?;
+ let geometric = hit.oriented_geometric_normal();
+ // The opt-in map uses the same reciprocal physical facet normal as its
+ // camera-side closures, including plain interfaces elsewhere in the job.
+ let normal = geometric;
+ if thin && model.roughness == 0.0 {
+ let (r, t) = smooth_sheet(input, path, normal)?;
+ let reflected = (r.x + r.y + r.z) / 3.0;
+ let transmitted = (t.x + t.y + t.z) / 3.0;
+ if reflected + transmitted == 0.0 {
+ return Ok(true);
+ }
+ let probability = reflected / (reflected + transmitted);
+ let reflection = map.random(path.depth, 2)[0] < probability;
+ let direction = if reflection {
+ path.flux = multiply(path.flux, r / probability);
+ dielectric::interface(path.ray.direction(), normal, ni, nt).map_err(error)?.reflected
+ } else {
+ path.flux = multiply(path.flux, t / (1.0 - probability));
+ path.ray.direction()
+ };
+ path.optical |= reflection || !input.shadow_transmission;
+ launch(task, path, index, hit, direction)?;
+ map.stage = Stage::Trace;
+ return Ok(false);
+ }
+ let Some(sample) = model.sample(path.ray.direction(), normal, ni, nt, wavelength(path)?, sample_uniforms(map, path)).map_err(model_error)? else {
+ return Ok(true);
+ };
+ if (sample.crosses && sample.direction.dot(geometric) >= 0.0) || (!sample.crosses && sample.direction.dot(geometric) <= 0.0) {
+ return Ok(true);
+ }
+ // Shared samples transport radiance; photons transport adjoint power.
+ let correction =
+ crate::glass_model::importance_normal_correction(path.ray.direction(), sample.direction, normal, geometric).map_err(model_error)?;
+ path.flux = path.flux * (sample.weight * correction * if sample.crosses { (nt / ni).powi(2) } else { 1.0 });
+ finite_flux(path.flux)?;
+ path.optical = true;
+ if thin && sample.crosses {
+ path.sheet = Some(Sheet { index, normal, geometric, direction: sample.direction, ray: path.ray, hit: raw });
+ path.depth += 1;
+ map.stage = Stage::Sheet;
+ return Ok(false);
+ }
+ if !thin && sample.crosses {
+ if hit.front_face {
+ *path.media.get_mut(path.len).ok_or_else(|| invalid("CPU caustic stack exceeds eight"))? = index;
+ path.len += 1;
+ } else {
+ path.len = path.len.checked_sub(1).ok_or_else(|| invalid("CPU caustic stack underflow"))?;
+ }
+ }
+ launch(task, path, index, hit, sample.direction)?;
+ map.stage = Stage::Trace;
+ Ok(false)
+}
+fn sheet(map: &mut Task, task: &ImageTask, path: &mut Path) -> job::Result<bool> {
+ let sheet = path.sheet.ok_or_else(|| invalid("CPU caustic rough sheet continuation missing"))?;
+ let input = task.options.dielectrics.get(sheet.index).ok_or_else(|| invalid("CPU caustic rough sheet material missing"))?;
+ let model = input.model.unwrap_or_default();
+ let cosine = sheet.direction.dot(sheet.normal).abs();
+ let distance = if input.thickness_mm == 0.0 {
+ 0.0
+ } else if cosine > 0.0 {
+ input.thickness_mm / cosine
+ } else {
+ return Err(invalid("CPU caustic rough sheet has no finite grazing distance"));
+ };
+ path.flux = multiply(path.flux, dielectric::attenuation(input.absorption_per_mm, distance).map_err(error)?);
+ let normal = if sheet.direction.dot(sheet.normal) < 0.0 { sheet.normal } else { -sheet.normal };
+ let geometric = if sheet.direction.dot(sheet.normal) < 0.0 { sheet.geometric } else { -sheet.geometric };
+ let hit = prepared(task)?.resolve_hit(sheet.ray, sheet.hit).map_err(error)?;
+ let side = if (-geometric).dot(hit.geometric_normal) > 0.0 { 1 } else { -1 };
+ candidate(map, hit.position, hit.geometric_normal, -sheet.direction, hit.body_index, ReceiverKind::Rough, side, path)?;
+ if path.depth + 1 >= map.options.max_depth {
+ return Ok(true);
+ }
+ let ni = ior(task, path, Some(sheet.index))?;
+ let Some(sample) = model.sample(sheet.direction, normal, ni, 1.0, wavelength(path)?, sample_uniforms(map, path)).map_err(model_error)? else {
+ return Ok(true);
+ };
+ if (sample.crosses && sample.direction.dot(geometric) >= 0.0) || (!sample.crosses && sample.direction.dot(geometric) <= 0.0) {
+ return Ok(true);
+ }
+ let correction = crate::glass_model::importance_normal_correction(sheet.direction, sample.direction, normal, geometric).map_err(model_error)?;
+ path.flux = path.flux * (sample.weight * correction * if sample.crosses { ni * ni } else { 1.0 });
+ finite_flux(path.flux)?;
+ if sample.crosses {
+ if sample.direction.dot(sheet.normal) * sample.direction.dot(sheet.geometric) <= 0.0 {
+ return Ok(true);
+ }
+ path.sheet = None;
+ launch(task, path, sheet.index, hit, sample.direction)?;
+ map.stage = Stage::Trace;
+ } else {
+ path.sheet = Some(Sheet { direction: sample.direction, ..sheet });
+ path.depth += 1;
+ }
+ Ok(false)
+}
+fn sort(map: &mut Task) -> job::Result<()> {
+ if map.width >= map.photons.len() {
+ map.scratch = Vec::new();
+ map.stage = Stage::Ready;
+ return Ok(());
+ }
+ if map.out == map.begin {
+ map.left = map.begin;
+ map.right = (map.begin + map.width).min(map.photons.len());
+ map.end = (map.right + map.width).min(map.photons.len());
+ }
+ let middle = (map.begin + map.width).min(map.photons.len());
+ let left = map.left < middle && (map.right >= map.end || map.photons.get(map.left).map(|p| p.cell) <= map.photons.get(map.right).map(|p| p.cell));
+ let index = if left {
+ let index = map.left;
+ map.left += 1;
+ index
+ } else {
+ let index = map.right;
+ map.right += 1;
+ index
+ };
+ *map.scratch.get_mut(map.out).ok_or_else(|| invalid("CPU caustic merge output"))? =
+ *map.photons.get(index).ok_or_else(|| invalid("CPU caustic merge input"))?;
+ map.out += 1;
+ if map.out == map.end {
+ map.begin = map.end;
+ if map.begin == map.photons.len() {
+ std::mem::swap(&mut map.photons, &mut map.scratch);
+ map.width = map.width.checked_mul(2).ok_or_else(|| error(TraceError::MemoryLimit))?;
+ map.begin = 0;
+ map.out = 0;
+ }
+ }
+ Ok(())
+}
+pub(super) fn step(task: &mut ImageTask) -> job::Result<()> {
+ let mut map = task.caustics.pop().ok_or_else(|| invalid("CPU caustic task missing"))?;
+ let result = advance(&mut map, task);
+ task.caustics.push(map);
+ result
+}
+fn advance(map: &mut Task, task: &mut ImageTask) -> job::Result<()> {
+ if map.stage == Stage::Trace {
+ let path = map.path.as_mut().ok_or_else(|| invalid("CPU caustic path missing"))?;
+ let complete = path
+ .cursor
+ .as_mut()
+ .ok_or_else(|| invalid("CPU caustic trace cursor missing"))?
+ .step_ordered(task.bvh.as_ref().ok_or_else(|| invalid("CPU caustic BVH missing"))?, &mut task.work, &task.cancel, |new, old| {
+ let optical = |hit: super::super::Hit| {
+ task.looks
+ .get(hit.primitive_index)
+ .is_some_and(|look| task.options.dielectrics.iter().any(|input| input.body_index == look.body_index))
+ };
+ match (optical(new), optical(old)) {
+ (false, true) => true,
+ (true, false) => false,
+ _ => new.primitive_index < old.primitive_index,
+ }
+ })
+ .map_err(error)?;
+ if let Some(hit) = complete {
+ path.hit = hit;
+ path.cursor = None;
+ path.emitter = None;
+ path.emitter_cursor = 0;
+ map.stage = Stage::Emitters;
+ }
+ return Ok(());
+ }
+ if map.stage == Stage::Origin && map.path.as_ref().and_then(|path| path.origin.as_ref()).is_some_and(|origin| !origin.ready()) {
+ let scene =
+ PreparedScene { bvh: task.bvh.as_ref().ok_or_else(|| invalid("CPU caustic BVH missing"))?, primitives: &task.looks, source: &task.scene };
+ map.path.as_mut().and_then(|path| path.origin.as_mut()).ok_or_else(|| invalid("CPU caustic origin classifier missing"))?.step(
+ task.glass.first().ok_or_else(|| invalid("CPU caustic glass certificate missing"))?,
+ &task.options.dielectrics,
+ scene,
+ &mut task.work,
+ &task.cancel,
+ )?;
+ return Ok(());
+ }
+ task.work.tick(&task.cancel).map_err(error)?;
+ match map.stage {
+ Stage::Emit => emit(map, task),
+ Stage::Emitters => {
+ let path = map.path.as_mut().ok_or_else(|| invalid("CPU caustic emitter path missing"))?;
+ if let Some(input) = task.options.area_lights.as_ref().and_then(|lights| lights.get(path.emitter_cursor)) {
+ if let Some((distance, position)) =
+ super::super::indirect::Rectangle::new(input).map_err(error)?.intersect(path.ray).map_err(error)?
+ && path.hit.is_none_or(|hit| distance < hit.geometry.distance)
+ && path.emitter.is_none_or(|(_, prior, _)| distance < prior)
+ {
+ path.emitter = Some((path.emitter_cursor, distance, position));
+ }
+ path.emitter_cursor += 1;
+ } else {
+ map.stage = Stage::Resolve;
+ }
+ Ok(())
+ }
+ Stage::Origin => {
+ let path = map.path.as_mut().ok_or_else(|| invalid("CPU caustic path missing"))?;
+ let (media, len, _) = path.origin.take().ok_or_else(|| invalid("CPU caustic origin missing"))?.result()?;
+ if path.verify_origin && (len != path.len || media.get(..len) != path.media.get(..path.len)) {
+ return Err(invalid("CPU caustic collision left its certified medium"));
+ }
+ path.media = media;
+ path.len = len;
+ path.verify_origin = false;
+ map.stage = Stage::Trace;
+ Ok(())
+ }
+ Stage::Resolve | Stage::Sheet => {
+ let mut path = map.path.take().ok_or_else(|| invalid("CPU caustic path missing"))?;
+ let done = if map.stage == Stage::Sheet { sheet(map, task, &mut path)? } else { resolve(map, task, &mut path)? };
+ let done = done || path.flux == Vec3::ZERO || path.depth >= map.options.max_depth;
+ map.path = Some(path);
+ if done {
+ map.finish_path()?;
+ }
+ Ok(())
+ }
+ Stage::Sort => sort(map),
+ Stage::Trace | Stage::Ready => Err(invalid("CPU caustic stage bypassed its continuation")),
+ }
+}
+
+#[derive(Default)]
+pub(super) struct Gather {
+ cell: Option<[i64; 3]>,
+ neighbor: u8,
+ index: usize,
+ end: usize,
+}
+fn next(task: &ImageTask, cursor: &mut Gather, position: Vec3) -> job::Result<Option<Option<(Photon, f64)>>> {
+ let map = task.caustics.first().filter(|map| map.ready()).ok_or_else(|| invalid("CPU caustic map is incomplete"))?;
+ let center = if let Some(center) = cursor.cell {
+ center
+ } else {
+ let center = cell(position, map.options.radius_mm)?;
+ cursor.cell = Some(center);
+ center
+ };
+ if cursor.index < cursor.end {
+ let photon = *map.photons.get(cursor.index).ok_or_else(|| invalid("CPU caustic gather index"))?;
+ cursor.index += 1;
+ return Ok(Some(Some((photon, map.options.radius_mm))));
+ }
+ if cursor.neighbor == 27 {
+ return Ok(None);
+ }
+ let n = i64::from(cursor.neighbor);
+ let key = [center[0] + n % 3 - 1, center[1] + (n / 3) % 3 - 1, center[2] + n / 9 - 1];
+ cursor.neighbor += 1;
+ cursor.index = map.photons.partition_point(|photon| photon.cell < key);
+ cursor.end = map.photons.partition_point(|photon| photon.cell <= key);
+ Ok(Some(None))
+}
+fn source_allows(task: &ImageTask, photon: Photon, position: Vec3) -> job::Result<bool> {
+ if photon.source == u32::MAX {
+ return Ok(true);
+ }
+ let input = task
+ .options
+ .punctual_lights
+ .as_ref()
+ .and_then(|lights| lights.get(photon.source as usize))
+ .ok_or_else(|| invalid("CPU caustic receiver source identity disappeared"))?;
+ Ok(position.dist(Vec3::new(input.position_mm[0], input.position_mm[1], input.position_mm[2])) >= input.minimum_distance_mm)
+}
+pub(super) fn gather(task: &ImageTask, cursor: &mut Gather, hit: SharedHit<'_>, view: Vec3) -> job::Result<Option<Vec3>> {
+ let Some(visit) = next(task, cursor, hit.position)? else { return Ok(None) };
+ let Some((photon, radius)) = visit else { return Ok(Some(Vec3::ZERO)) };
+ let geometric = hit.oriented_geometric_normal();
+ if photon.kind != ReceiverKind::Opaque
+ || photon.body != hit.body_index
+ || !source_allows(task, photon, hit.position)?
+ || photon.position.dist(hit.position) > radius
+ || (photon.position - hit.position).dot(geometric).abs() > radius * 0.1
+ || photon.normal.dot(geometric) <= 0.0
+ || geometric.dot(photon.incoming) <= 0.0
+ || hit.shading_normal.dot(photon.incoming) <= 0.0
+ {
+ return Ok(Some(Vec3::ZERO));
+ }
+ let brdf = hit.surface.brdf(hit.shading_normal, view, photon.incoming).map_err(|_| invalid("CPU caustic receiver BRDF is invalid"))?;
+ let measure = crate::glass_model::surface_normal_measure(photon.incoming, hit.shading_normal, geometric).map_err(model_error)?;
+ Ok(Some(multiply(brdf, photon.flux) * (measure / (PI * radius.powi(2)))))
+}
+
+#[derive(Clone, Copy)]
+pub(super) struct RoughReceiver {
+ pub position: Vec3,
+ pub canonical: Vec3,
+ pub geometric: Vec3,
+ pub normal: Vec3,
+ pub incident: Vec3,
+ pub body: usize,
+ pub side: i8,
+ pub model: crate::glass_model::GlassModel,
+ pub ni: f64,
+ pub nt: f64,
+ pub wavelength_nm: f64,
+}
+pub(super) fn gather_rough(task: &ImageTask, cursor: &mut Gather, receiver: RoughReceiver) -> job::Result<Option<Vec3>> {
+ let Some(visit) = next(task, cursor, receiver.position)? else { return Ok(None) };
+ let Some((photon, radius)) = visit else { return Ok(Some(Vec3::ZERO)) };
+ if photon.kind != ReceiverKind::Rough
+ || photon.body != receiver.body
+ || photon.side != receiver.side
+ || !source_allows(task, photon, receiver.position)?
+ || photon.position.dist(receiver.position) > radius
+ || (photon.position - receiver.position).dot(receiver.canonical).abs() > radius * 0.1
+ || photon.normal.dot(receiver.canonical) <= 0.0
+ || photon.incoming.dot(receiver.normal) * photon.incoming.dot(receiver.geometric) <= 0.0
+ {
+ return Ok(Some(Vec3::ZERO));
+ }
+ let value = receiver
+ .model
+ .evaluate(receiver.incident, photon.incoming, receiver.normal, receiver.ni, receiver.nt, receiver.wavelength_nm)
+ .map_err(model_error)?
+ .value;
+ let measure = crate::glass_model::surface_normal_measure(photon.incoming, receiver.normal, receiver.geometric).map_err(model_error)?;
+ Ok(Some(photon.flux * (value * measure / (PI * radius.powi(2)))))
+}
+pub(super) fn gather_volume(
+ task: &ImageTask,
+ cursor: &mut Gather,
+ position: Vec3,
+ body: usize,
+ incident: Vec3,
+ scattering: crate::transmission::subsurface::Subsurface,
+) -> job::Result<Option<Vec3>> {
+ let Some(visit) = next(task, cursor, position)? else { return Ok(None) };
+ let Some((photon, radius)) = visit else { return Ok(Some(Vec3::ZERO)) };
+ if photon.kind != ReceiverKind::Volume
+ || photon.body != body
+ || photon.position.dist(position) > radius
+ || !source_allows(task, photon, position)?
+ {
+ return Ok(Some(Vec3::ZERO));
+ }
+ let phase = scattering.phase(incident.dot(photon.incoming).clamp(-1.0, 1.0)).map_err(model_error)?;
+ let kernel = crate::glass_model::volume_photon_kernel(radius, scattering.scattering_per_mm).map_err(model_error)?;
+ Ok(Some(photon.flux * (phase * kernel)))
+}
diff --git a/crates/render/src/raytrace/image_glass_lighting.rs b/crates/render/src/raytrace/image_glass_lighting.rs
new file mode 100644
index 0000000000..47ca46862c
--- /dev/null
+++ b/crates/render/src/raytrace/image_glass_lighting.rs
@@ -0,0 +1,436 @@
+//! Cooperative hard-source connections at physical optical and HG vertices.
+//! Finite emitters and environment endpoints retain their BSDF-only technique.
+use super::*;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(super) enum InterfaceKind {
+ Closed,
+ SheetExternal,
+ SheetInternal,
+}
+#[derive(Clone, Copy)]
+pub(super) struct Interface {
+ pub index: usize,
+ pub position: Vec3,
+ pub canonical: Vec3,
+ pub normal: Vec3,
+ pub geometric: Vec3,
+ pub incident: Vec3,
+ pub ni: f64,
+ pub nt: f64,
+ pub next_medium: Option<usize>,
+ pub wavelength_nm: f64,
+ pub kind: InterfaceKind,
+}
+#[derive(Clone, Copy)]
+pub(super) enum Event {
+ Interface(Interface),
+ Medium { index: usize, position: Vec3, incoming: Vec3 },
+}
+impl Event {
+ fn position(self) -> Vec3 {
+ match self {
+ Self::Interface(event) => event.position,
+ Self::Medium { position, .. } => position,
+ }
+ }
+}
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Phase {
+ Gather,
+ Directional,
+ Punctual,
+ Trace,
+ Resolve,
+ Select,
+ Emitters,
+ Add,
+ Done,
+}
+pub(super) struct Context {
+ event: Event,
+ phase: Phase,
+ after_shadow: Phase,
+ light: usize,
+ pending: Vec3,
+ medium: Option<usize>,
+ from: Vec3,
+ endpoint: Option<Vec3>,
+ visibility: Option<Ray>,
+ hit: Option<super::super::super::Hit>,
+ selector: usize,
+ selected: Option<usize>,
+ interfaces: u8,
+ emitter: usize,
+}
+#[cfg(test)]
+impl Context {
+ pub(super) fn pending_probe(&self) -> Option<(u8, Vec3)> {
+ (self.phase == Phase::Add).then_some({
+ (
+ match self.event {
+ Event::Interface(event) => match event.kind {
+ InterfaceKind::Closed => 1,
+ InterfaceKind::SheetExternal => 2,
+ InterfaceKind::SheetInternal => 3,
+ },
+ Event::Medium { .. } => 4,
+ },
+ self.pending,
+ )
+ })
+ }
+}
+fn model_error(error: impl std::fmt::Display) -> JobError {
+ JobError::new(ErrorCode::InvalidScene, error.to_string())
+}
+pub(super) fn begin(task: &ImageTask, state: &mut State, event: Event) -> bool {
+ if !vertex_lighting(task, state)
+ || (task.caustics.is_empty() && task.lights.lights().is_empty() && task.options.punctual_lights.as_ref().is_none_or(Vec::is_empty))
+ {
+ return false;
+ }
+ state.caustic_gather = Default::default();
+ state.glass_lighting = Some(Context {
+ event,
+ phase: if task.caustics.is_empty() { Phase::Directional } else { Phase::Gather },
+ after_shadow: Phase::Directional,
+ light: 0,
+ pending: Vec3::ZERO,
+ medium: None,
+ from: event.position(),
+ endpoint: None,
+ visibility: None,
+ hit: None,
+ selector: 0,
+ selected: None,
+ interfaces: 0,
+ emitter: 0,
+ });
+ state.stage = Stage::GlassLighting;
+ true
+}
+fn scattering(task: &ImageTask, index: usize) -> job::Result<crate::transmission::subsurface::Subsurface> {
+ task.options
+ .dielectrics
+ .get(index)
+ .and_then(|input| input.subsurface)
+ .filter(|scattering| scattering.active())
+ .ok_or_else(|| invalid("CPU hard-source HG receiver lost its medium"))
+}
+fn gather(task: &ImageTask, state: &mut State, event: Event) -> job::Result<Option<Vec3>> {
+ match event {
+ Event::Interface(event) => {
+ let input = task.options.dielectrics.get(event.index).ok_or_else(|| invalid("CPU rough photon receiver disappeared"))?;
+ let outward = if event.kind == InterfaceKind::SheetInternal { -event.geometric } else { event.geometric };
+ let side = if event.kind == InterfaceKind::Closed {
+ 0
+ } else if outward.dot(event.canonical) > 0.0 {
+ 1
+ } else {
+ -1
+ };
+ super::super::caustics::gather_rough(
+ task,
+ &mut state.caustic_gather,
+ super::super::caustics::RoughReceiver {
+ position: event.position,
+ canonical: event.canonical,
+ geometric: event.geometric,
+ normal: event.normal,
+ incident: event.incident,
+ body: input.body_index,
+ side,
+ model: input.model.unwrap_or_default(),
+ ni: event.ni,
+ nt: event.nt,
+ wavelength_nm: event.wavelength_nm,
+ },
+ )
+ }
+ Event::Medium { index, position, incoming } => {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU HG photon receiver disappeared"))?;
+ super::super::caustics::gather_volume(task, &mut state.caustic_gather, position, input.body_index, incoming, scattering(task, index)?)
+ }
+ }
+}
+fn response(task: &ImageTask, state: &State, event: Event, direction: Vec3) -> job::Result<(f64, Option<usize>)> {
+ match event {
+ Event::Interface(event) => {
+ let geometric_cosine = direction.dot(event.geometric);
+ if direction.dot(event.normal) * geometric_cosine <= 0.0
+ || (event.kind == InterfaceKind::SheetExternal && geometric_cosine <= 0.0)
+ || (event.kind == InterfaceKind::SheetInternal && geometric_cosine >= 0.0)
+ {
+ return Ok((0.0, None));
+ }
+ let input = task.options.dielectrics.get(event.index).ok_or_else(|| invalid("CPU hard-source glass material disappeared"))?;
+ let value = input
+ .model
+ .unwrap_or_default()
+ .evaluate_projected(event.incident, direction, event.normal, event.ni, event.nt, event.wavelength_nm)
+ .map_err(model_error)?
+ .value;
+ let medium = if event.kind != InterfaceKind::Closed {
+ None
+ } else if geometric_cosine > 0.0 {
+ current(state.optical.as_ref().ok_or_else(|| invalid("CPU hard-source optical stack missing"))?)?
+ } else {
+ event.next_medium
+ };
+ Ok((value, medium))
+ }
+ Event::Medium { index, incoming, .. } => {
+ Ok((scattering(task, index)?.phase(incoming.dot(direction).clamp(-1.0, 1.0)).map_err(model_error)?, Some(index)))
+ }
+ }
+}
+fn cursor(task: &ImageTask, state: &State, event: Event, ray: Ray) -> job::Result<TraceCursor> {
+ match event {
+ Event::Interface(event) => {
+ let region = task.glass.first().ok_or_else(|| invalid("CPU hard-source optical certificate missing"))?.region(event.index)?;
+ Ok(TraceCursor::from_plane(ray, region.primitive_begin..region.primitive_end, unmapped(task, state)?.vertices))
+ }
+ Event::Medium { .. } => Ok(TraceCursor::new(ray, false)),
+ }
+}
+fn queue(
+ task: &ImageTask,
+ state: &mut State,
+ context: &mut Context,
+ direction: Vec3,
+ radiance: Vec3,
+ endpoint: Option<Vec3>,
+ next: Phase,
+) -> job::Result<()> {
+ let (value, medium) = response(task, state, context.event, direction)?;
+ context.pending = multiply(state.throughput, radiance) * value;
+ super::super::super::lighting::validate_radiance(context.pending).map_err(error)?;
+ context.after_shadow = next;
+ if context.pending == Vec3::ZERO {
+ context.phase = next;
+ return Ok(());
+ }
+ let position = context.event.position();
+ let (direction, far) = if let Some(endpoint) = endpoint {
+ let delta = endpoint - position;
+ let distance = delta.len();
+ if !distance.is_finite() || distance.next_down() <= 0.0_f64.next_up() || delta.dot(direction) <= 0.0 {
+ return Err(invalid("CPU hard-source finite physical shadow collapsed"));
+ }
+ (delta, distance.next_down())
+ } else {
+ (direction, super::super::super::MAX_DISTANCE_MM)
+ };
+ let ray = Ray::new(position, direction, 0.0_f64.next_up(), far).map_err(error)?;
+ state.cursor = Some(cursor(task, state, context.event, ray)?);
+ state.shadow_ray = Some(ray);
+ context.medium = medium;
+ context.from = position;
+ context.endpoint = endpoint;
+ context.visibility = Some(ray);
+ context.hit = None;
+ context.interfaces = 0;
+ context.emitter = 0;
+ context.phase = Phase::Trace;
+ Ok(())
+}
+fn attenuate(task: &ImageTask, context: &mut Context, to: Vec3) -> job::Result<()> {
+ if let Some(index) = context.medium {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU hard-source shadow medium disappeared"))?;
+ let distance = context.from.dist(to);
+ context.pending = multiply(context.pending, dielectric::attenuation(input.absorption_per_mm, distance).map_err(error)?);
+ if let Some(scattering) = input.subsurface.filter(|scattering| scattering.active()) {
+ context.pending = context.pending * scattering.survival(distance).map_err(model_error)?;
+ }
+ }
+ context.from = to;
+ Ok(())
+}
+fn advance(task: &mut ImageTask, state: &mut State, context: &mut Context) -> job::Result<()> {
+ if context.phase == Phase::Trace {
+ let looks = &task.looks;
+ let inputs = &task.options.dielectrics;
+ let result = state
+ .cursor
+ .as_mut()
+ .ok_or_else(|| invalid("CPU hard-source shadow cursor missing"))?
+ .step_ordered(
+ task.bvh.as_ref().ok_or_else(|| invalid("CPU hard-source shadow BVH missing"))?,
+ &mut task.work,
+ &task.cancel,
+ |new, old| {
+ let optical = |hit: super::super::super::Hit| {
+ looks.get(hit.primitive_index).is_some_and(|look| inputs.iter().any(|input| input.body_index == look.body_index))
+ };
+ match (optical(new), optical(old)) {
+ (false, true) => true,
+ (true, false) => false,
+ _ => new.primitive_index < old.primitive_index,
+ }
+ },
+ )
+ .map_err(error)?;
+ if let Some(hit) = result {
+ state.cursor = None;
+ context.hit = hit;
+ context.phase = Phase::Resolve;
+ }
+ return Ok(());
+ }
+ task.work.tick(&task.cancel).map_err(error)?;
+ match context.phase {
+ Phase::Gather => {
+ if let Some(value) = gather(task, state, context.event)? {
+ state.radiance += multiply(state.throughput, value);
+ super::super::super::lighting::validate_radiance(state.radiance).map_err(error)?;
+ } else {
+ context.phase = Phase::Directional;
+ }
+ }
+ Phase::Directional => {
+ if let Some(light) = task.lights.lights().get(context.light) {
+ context.light += 1;
+ queue(task, state, context, light.direction(), light.color() * light.intensity(), None, Phase::Directional)?;
+ } else {
+ context.light = 0;
+ context.phase = Phase::Punctual;
+ }
+ }
+ Phase::Punctual => {
+ if let Some(input) = task.options.punctual_lights.as_ref().and_then(|lights| lights.get(context.light)) {
+ context.light += 1;
+ let sample = input.light().map_err(error)?.sample(context.event.position()).map_err(error)?;
+ if let Some(why) = sample.omitted {
+ match why {
+ super::super::super::punctual::OmittedSample::NearSource => {
+ task.punctual_diagnostics.near_source = task.punctual_diagnostics.near_source.saturating_add(1);
+ }
+ super::super::super::punctual::OmittedSample::RadianceLimit => {
+ task.punctual_diagnostics.radiance_limit = task.punctual_diagnostics.radiance_limit.saturating_add(1);
+ }
+ }
+ } else {
+ queue(
+ task,
+ state,
+ context,
+ sample.direction,
+ sample.incident_linear_srgb,
+ Some(Vec3::new(input.position_mm[0], input.position_mm[1], input.position_mm[2])),
+ Phase::Punctual,
+ )?;
+ }
+ } else {
+ context.phase = Phase::Done;
+ }
+ }
+ Phase::Resolve => {
+ if let Some(raw) = context.hit {
+ let ray = state.shadow_ray.ok_or_else(|| invalid("CPU hard-source visibility ray missing"))?;
+ let hit = PreparedScene {
+ bvh: task.bvh.as_ref().ok_or_else(|| invalid("CPU hard-source visibility BVH missing"))?,
+ primitives: &task.looks,
+ source: &task.scene,
+ }
+ .resolve_hit(ray, raw)
+ .map_err(error)?;
+ attenuate(task, context, hit.position)?;
+ context.selector = 0;
+ context.selected = None;
+ context.phase = Phase::Select;
+ } else {
+ if let Some(endpoint) = context.endpoint {
+ attenuate(task, context, endpoint)?;
+ } else if context.medium.is_some() {
+ return Err(invalid("CPU hard-source shadow escaped its certified current medium"));
+ }
+ context.phase = Phase::Emitters;
+ }
+ }
+ Phase::Select => {
+ let ray = state.shadow_ray.ok_or_else(|| invalid("CPU hard-source visibility ray missing"))?;
+ let hit = PreparedScene {
+ bvh: task.bvh.as_ref().ok_or_else(|| invalid("CPU hard-source visibility BVH missing"))?,
+ primitives: &task.looks,
+ source: &task.scene,
+ }
+ .resolve_hit(ray, context.hit.ok_or_else(|| invalid("CPU hard-source visibility hit missing"))?)
+ .map_err(error)?;
+ if let Some(input) = task.options.dielectrics.get(context.selector) {
+ if input.body_index == hit.body_index && input.body_name == hit.body_name {
+ context.selected = Some(context.selector);
+ context.selector = task.options.dielectrics.len();
+ } else {
+ context.selector += 1;
+ }
+ return Ok(());
+ }
+ if let Some(index) = context.selected {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU hard-source sheet material disappeared"))?;
+ if input.boundary == job::DielectricBoundary::ThinSheet
+ && input.shadow_transmission
+ && input.model.unwrap_or_default().roughness == 0.0
+ {
+ let (_, _, transmission) = dielectric::modeled_sheet(ray.direction(), hit.oriented_geometric_normal(), input).map_err(error)?;
+ context.pending = multiply(context.pending, transmission);
+ context.interfaces = context
+ .interfaces
+ .checked_add(1)
+ .filter(|count| *count <= 16)
+ .ok_or_else(|| invalid("CPU hard-source shadow exceeds sixteen thin interfaces"))?;
+ if context.pending != Vec3::ZERO {
+ let (next_ray, next_cursor) = interface_cursor(task, index, hit, ray.direction(), context.endpoint, false)?;
+ state.shadow_ray = Some(next_ray);
+ state.cursor = Some(next_cursor);
+ context.phase = Phase::Trace;
+ return Ok(());
+ }
+ }
+ }
+ // A delta-source connection cannot bend through another closed
+ // interface. Those missing source paths belong to the photon map.
+ context.pending = Vec3::ZERO;
+ context.phase = Phase::Add;
+ }
+ Phase::Emitters => {
+ if let Some(input) = task.options.area_lights.as_ref().and_then(|lights| lights.get(context.emitter)) {
+ context.emitter += 1;
+ let rectangle = Rectangle::new(input).map_err(error)?;
+ if !rectangle.on_plane(context.event.position())
+ && rectangle
+ .intersect(context.visibility.ok_or_else(|| invalid("CPU hard-source analytic visibility ray missing"))?)
+ .map_err(error)?
+ .is_some()
+ {
+ context.pending = Vec3::ZERO;
+ context.phase = Phase::Add;
+ }
+ } else {
+ context.phase = Phase::Add;
+ }
+ }
+ Phase::Add => {
+ state.radiance += context.pending;
+ super::super::super::lighting::validate_radiance(state.radiance).map_err(error)?;
+ state.shadow_ray = None;
+ context.phase = context.after_shadow;
+ }
+ Phase::Done => {}
+ Phase::Trace => return Err(invalid("CPU hard-source shadow bypassed its cooperative cursor")),
+ }
+ Ok(())
+}
+pub(super) fn step(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
+ let mut context = state.glass_lighting.take().ok_or_else(|| invalid("CPU hard-source vertex context missing"))?;
+ let result = advance(task, state, &mut context);
+ if result.is_ok() && context.phase == Phase::Done {
+ return match context.event {
+ Event::Interface(event) if event.kind == InterfaceKind::SheetInternal => advanced::resume_sheet(task, state, event),
+ Event::Interface(event) => advanced::resume_surface(task, state, event),
+ Event::Medium { index, position, incoming } => scattering::resume(task, state, index, position, incoming),
+ };
+ }
+ state.glass_lighting = Some(context);
+ result
+}
diff --git a/crates/render/src/raytrace/image_glass_model.rs b/crates/render/src/raytrace/image_glass_model.rs
new file mode 100644
index 0000000000..f9aebdeea5
--- /dev/null
+++ b/crates/render/src/raytrace/image_glass_model.rs
@@ -0,0 +1,300 @@
+//! Explicit rough and spectral dielectric events on the existing finite path.
+//! Spectral paths use one RGB hero wavelength; inactive models retain the old stream.
+use super::*;
+use crate::glass_model::WAVELENGTHS_NM;
+
+#[derive(Clone, Copy)]
+pub(super) struct SheetWalk {
+ index: usize,
+ normal: Vec3,
+ geometric: Vec3,
+ direction: Vec3,
+}
+fn model_error(error: impl std::fmt::Display) -> JobError {
+ JobError::new(ErrorCode::InvalidScene, error.to_string())
+}
+fn active(input: &job::DielectricOptions) -> bool {
+ input.model.is_some_and(|model| model.roughness > 0.0 || model.spectral())
+}
+pub(super) fn required(task: &ImageTask, state: &State, index: usize) -> job::Result<bool> {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU advanced glass material disappeared"))?;
+ let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU advanced glass stack missing"))?;
+ let incident_spectral =
+ current(optical)?.and_then(|index| task.options.dielectrics.get(index)).and_then(|input| input.model).is_some_and(|model| model.spectral());
+ Ok(active(input) || incident_spectral || optical.spectral_channel.is_some())
+}
+fn wavelength(state: &State) -> job::Result<f64> {
+ let index = state.optical.as_ref().and_then(|optical| optical.spectral_channel).unwrap_or(1);
+ WAVELENGTHS_NM.get(usize::from(index)).copied().ok_or_else(|| invalid("CPU glass wavelength channel is invalid"))
+}
+fn select_spectrum(task: &ImageTask, state: &mut State, index: usize) -> job::Result<()> {
+ let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU spectral glass stack missing"))?;
+ if optical.spectral_channel.is_some() {
+ return Ok(());
+ }
+ let spectral = |index: usize| task.options.dielectrics.get(index).and_then(|input| input.model).is_some_and(|model| model.spectral());
+ if !spectral(index) && !current(optical)?.is_some_and(spectral) {
+ return Ok(());
+ }
+ let [draw, _] = variates(task, state, 0x4100)?;
+ let channel = (draw * 3.0) as u8;
+ let mask = match channel {
+ 0 => Vec3::new(3.0, 0.0, 0.0),
+ 1 => Vec3::new(0.0, 3.0, 0.0),
+ 2 => Vec3::new(0.0, 0.0, 3.0),
+ _ => return Err(invalid("CPU glass wavelength draw is invalid")),
+ };
+ state.throughput = multiply(state.throughput, mask);
+ state.optical.as_mut().ok_or_else(|| invalid("CPU spectral glass stack missing"))?.spectral_channel = Some(channel);
+ Ok(())
+}
+fn ior(task: &ImageTask, state: &State, index: Option<usize>) -> job::Result<f64> {
+ let Some(index) = index else { return Ok(1.0) };
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU spectral medium index is invalid"))?;
+ input.model.unwrap_or_default().ior(input.ior, wavelength(state)?).map_err(model_error)
+}
+fn uniforms(task: &ImageTask, state: &State) -> job::Result<[f64; 3]> {
+ let [branch, x] = variates(task, state, 0x4000)?;
+ let [y, _] = variates(task, state, 0x4001)?;
+ Ok([x, y, branch])
+}
+fn apply_weight(state: &mut State, weight: f64) -> job::Result<()> {
+ if !weight.is_finite() || weight < 0.0 {
+ return Err(invalid("CPU advanced glass has a nonfinite or negative weight"));
+ }
+ state.throughput = state.throughput * weight;
+ super::super::super::lighting::validate_radiance(state.throughput).map_err(error)
+}
+fn finish(
+ task: &ImageTask,
+ state: &mut State,
+ index: usize,
+ direction: Vec3,
+ pdf: f64,
+ entering: Option<bool>,
+ preserve_pdf: bool,
+) -> job::Result<()> {
+ let hit = unmapped(task, state)?;
+ let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU advanced glass stack missing"))?;
+ if let Some(enter) = entering {
+ if enter {
+ *optical.media.get_mut(optical.len).ok_or_else(|| invalid("CPU advanced glass stack exceeds eight"))? = index;
+ optical.len += 1;
+ } else {
+ optical.len = optical.len.checked_sub(1).ok_or_else(|| invalid("CPU advanced glass stack underflow"))?;
+ }
+ }
+ // Finite emitters and environment endpoints remain BSDF-only here. The
+ // hard-source connection has a discrete measure and does not compete with
+ // those sampled endpoints, even when the rough proposal has finite density.
+ if !preserve_pdf {
+ optical.delta = true;
+ state.previous_pdf = pdf;
+ state.previous_position = hit.position;
+ }
+ optical.segment_start = hit.position;
+ optical.source_plane = Some(hit.vertices);
+ optical.sheet = None;
+ if state.throughput == Vec3::ZERO {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ let (ray, cursor) = interface_cursor(task, index, hit, direction, None, true)?;
+ state.ray = Some(ray);
+ state.cursor = Some(cursor);
+ state.hit = None;
+ state.depth += 1;
+ state.stage = Stage::Trace;
+ Ok(())
+}
+
+pub(super) fn surface(task: &ImageTask, state: &mut State, index: usize) -> job::Result<()> {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU advanced glass material disappeared"))?;
+ let thin = input.boundary == job::DielectricBoundary::ThinSheet;
+ if thin && input.model.unwrap_or_default().roughness == 0.0 {
+ if !continuing(task, state)? {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ let hit = unmapped(task, state)?;
+ let direction = state.ray.ok_or_else(|| invalid("CPU modeled sheet incident ray missing"))?.direction();
+ let normal = if advanced_normals(task) {
+ hit.oriented_geometric_normal()
+ } else {
+ dielectric::shaded_interface(direction, hit.oriented_geometric_normal(), hit.shading_normal, 1.0, input.ior).map_err(error)?.1
+ };
+ return smooth_sheet(task, state, index, normal);
+ }
+ select_spectrum(task, state, index)?;
+ let hit = unmapped(task, state)?;
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU advanced glass material disappeared"))?;
+ let model = input.model.unwrap_or_default();
+ let direction = state.ray.ok_or_else(|| invalid("CPU advanced glass incident ray missing"))?.direction();
+ let geometric = hit.oriented_geometric_normal();
+ let optical = state.optical.as_ref().ok_or_else(|| invalid("CPU advanced glass stack missing"))?;
+ let medium = current(optical)?;
+ let region = task.glass.first().ok_or_else(|| invalid("CPU advanced glass certificate missing"))?.region(index)?;
+ let thin = input.boundary == job::DielectricBoundary::ThinSheet;
+ let next = if thin {
+ if medium.is_some() {
+ return Err(invalid("CPU thin advanced glass cannot be inside a closed medium"));
+ }
+ Some(index)
+ } else if hit.front_face {
+ if medium != region.parent {
+ return Err(invalid("CPU advanced glass entered outside its certified parent"));
+ }
+ Some(index)
+ } else {
+ if medium != Some(index) {
+ return Err(invalid("CPU advanced glass exit does not match the current medium"));
+ }
+ region.parent
+ };
+ let ni = ior(task, state, medium)?;
+ let nt = ior(task, state, next)?;
+ let event = glass_lighting::Interface {
+ index,
+ position: hit.position,
+ canonical: hit.geometric_normal,
+ normal: geometric,
+ geometric,
+ incident: direction,
+ ni,
+ nt,
+ next_medium: next,
+ wavelength_nm: wavelength(state)?,
+ kind: if thin { glass_lighting::InterfaceKind::SheetExternal } else { glass_lighting::InterfaceKind::Closed },
+ };
+ if model.roughness > 0.0 && glass_lighting::begin(task, state, glass_lighting::Event::Interface(event)) {
+ return Ok(());
+ }
+ resume_surface(task, state, event)
+}
+pub(super) fn resume_surface(task: &ImageTask, state: &mut State, event: glass_lighting::Interface) -> job::Result<()> {
+ if !continuing(task, state)? {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ let input = task.options.dielectrics.get(event.index).ok_or_else(|| invalid("CPU advanced glass material disappeared"))?;
+ let thin = event.kind == glass_lighting::InterfaceKind::SheetExternal;
+ let Some(sample) = input
+ .model
+ .unwrap_or_default()
+ .sample(event.incident, event.normal, event.ni, event.nt, event.wavelength_nm, uniforms(task, state)?)
+ .map_err(model_error)?
+ else {
+ state.stage = Stage::Commit;
+ return Ok(());
+ };
+ if (sample.crosses && sample.direction.dot(event.geometric) >= 0.0) || (!sample.crosses && sample.direction.dot(event.geometric) <= 0.0) {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ apply_weight(state, sample.weight)?;
+ state.sampled_continuous |= !sample.delta;
+ if thin && sample.crosses {
+ state.optical.as_mut().ok_or_else(|| invalid("CPU rough sheet stack missing"))?.sheet =
+ Some(SheetWalk { index: event.index, normal: event.normal, geometric: event.geometric, direction: sample.direction });
+ state.depth += 1;
+ state.stage = Stage::GlassSheet;
+ return Ok(());
+ }
+ let entering = if !thin && sample.crosses { Some(unmapped(task, state)?.front_face) } else { None };
+ finish(task, state, event.index, sample.direction, sample.pdf, entering, false)
+}
+
+fn smooth_sheet(task: &ImageTask, state: &mut State, index: usize, normal: Vec3) -> job::Result<()> {
+ let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU modeled sheet material disappeared"))?;
+ let direction = state.ray.ok_or_else(|| invalid("CPU modeled sheet incident ray missing"))?.direction();
+ let (interface, reflected, transmitted) = dielectric::modeled_sheet(direction, normal, input).map_err(error)?;
+ let probability = thin_probability(reflected, transmitted)?;
+ let [draw, _] = variates(task, state, 0x4000)?;
+ let (outgoing, preserve) = if draw < probability {
+ state.throughput = multiply(state.throughput, reflected / probability);
+ (interface.reflected, false)
+ } else {
+ let mass = 1.0 - probability;
+ if mass <= 0.0 {
+ return Err(invalid("CPU modeled sheet transmission has zero sampling mass"));
+ }
+ state.throughput = multiply(state.throughput, transmitted / mass);
+ if input.shadow_transmission {
+ state.previous_pdf *= mass;
+ }
+ (direction, input.shadow_transmission)
+ };
+ super::super::super::lighting::validate_radiance(state.throughput).map_err(error)?;
+ finish(task, state, index, outgoing, 0.0, None, preserve)
+}
+
+pub(super) fn sheet_step(task: &ImageTask, state: &mut State) -> job::Result<()> {
+ let walk = state.optical.as_ref().and_then(|optical| optical.sheet).ok_or_else(|| invalid("CPU rough sheet continuation missing"))?;
+ let input = task.options.dielectrics.get(walk.index).ok_or_else(|| invalid("CPU rough sheet material disappeared"))?;
+ let cosine = walk.direction.dot(walk.normal).abs();
+ let distance = if input.thickness_mm == 0.0 {
+ 0.0
+ } else if cosine > 0.0 {
+ input.thickness_mm / cosine
+ } else {
+ return Err(invalid("CPU rough sheet has no finite grazing optical distance"));
+ };
+ state.throughput = multiply(state.throughput, dielectric::attenuation(input.absorption_per_mm, distance).map_err(error)?);
+ let normal = if walk.direction.dot(walk.normal) < 0.0 { walk.normal } else { -walk.normal };
+ let geometric = if walk.direction.dot(walk.normal) < 0.0 { walk.geometric } else { -walk.geometric };
+ let hit = unmapped(task, state)?;
+ let event = glass_lighting::Interface {
+ index: walk.index,
+ position: hit.position,
+ canonical: hit.geometric_normal,
+ normal,
+ geometric,
+ incident: walk.direction,
+ ni: ior(task, state, Some(walk.index))?,
+ nt: 1.0,
+ next_medium: None,
+ wavelength_nm: wavelength(state)?,
+ kind: glass_lighting::InterfaceKind::SheetInternal,
+ };
+ if state.throughput == Vec3::ZERO {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ if glass_lighting::begin(task, state, glass_lighting::Event::Interface(event)) {
+ return Ok(());
+ }
+ resume_sheet(task, state, event)
+}
+pub(super) fn resume_sheet(task: &ImageTask, state: &mut State, event: glass_lighting::Interface) -> job::Result<()> {
+ if !continuing(task, state)? {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ let walk = state.optical.as_ref().and_then(|optical| optical.sheet).ok_or_else(|| invalid("CPU rough sheet continuation missing"))?;
+ let model =
+ task.options.dielectrics.get(event.index).and_then(|input| input.model).ok_or_else(|| invalid("CPU rough sheet model disappeared"))?;
+ let Some(sample) =
+ model.sample(event.incident, event.normal, event.ni, event.nt, event.wavelength_nm, uniforms(task, state)?).map_err(model_error)?
+ else {
+ state.stage = Stage::Commit;
+ return Ok(());
+ };
+ if (sample.crosses && sample.direction.dot(event.geometric) >= 0.0) || (!sample.crosses && sample.direction.dot(event.geometric) <= 0.0) {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ apply_weight(state, sample.weight)?;
+ state.sampled_continuous |= !sample.delta;
+ if sample.crosses {
+ if sample.direction.dot(walk.normal) * sample.direction.dot(walk.geometric) <= 0.0 {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ return finish(task, state, walk.index, sample.direction, sample.pdf, None, false);
+ }
+ state.optical.as_mut().ok_or_else(|| invalid("CPU rough sheet continuation missing"))?.sheet =
+ Some(SheetWalk { direction: sample.direction, ..walk });
+ state.depth += 1;
+ state.stage = Stage::GlassSheet;
+ Ok(())
+}
diff --git a/crates/render/src/raytrace/image_indirect.rs b/crates/render/src/raytrace/image_indirect.rs
index 855f71b716..0164f6a41b 100644
--- a/crates/render/src/raytrace/image_indirect.rs
+++ b/crates/render/src/raytrace/image_indirect.rs
@@ -1,6 +1,10 @@
//! One prepaid opaque path continuation. No ray queue, recursion or image storage.
use super::*;
use crate::raytrace::indirect::{self, Rectangle, multiply, power_weight};
+#[path = "image_glass_model.rs"]
+mod advanced;
+#[path = "image_glass_lighting.rs"]
+mod glass_lighting;
#[path = "image_scattering.rs"]
mod scattering;
#[path = "image_volume.rs"]
@@ -21,12 +25,15 @@ enum Stage {
Emitters,
Resolve,
Glass,
+ GlassSheet,
+ GlassLighting,
ShadowBeer,
ShadowGlass,
Effects,
Maps,
Aging,
Emission,
+ Caustics,
Directional,
Punctual,
Area,
@@ -63,6 +70,9 @@ pub(super) struct State {
shadow_ray: Option<Ray>,
shadow_emitter: usize,
shadow_excluded: Option<usize>,
+ caustic_gather: super::caustics::Gather,
+ glass_lighting: Option<glass_lighting::Context>,
+ sampled_continuous: bool,
}
impl Default for State {
fn default() -> Self {
@@ -91,6 +101,9 @@ impl Default for State {
shadow_ray: None,
shadow_emitter: 0,
shadow_excluded: None,
+ caustic_gather: Default::default(),
+ glass_lighting: None,
+ sampled_continuous: false,
}
}
}
@@ -129,6 +142,12 @@ pub(super) struct MediumProbe {
}
#[cfg(test)]
impl State {
+ pub(super) fn hard_light_probe(&self) -> Option<(u8, u8, Vec3, Vec3)> {
+ self.glass_lighting.as_ref()?.pending_probe().map(|(kind, pending)| (self.depth, kind, pending, self.radiance))
+ }
+ pub(super) fn continuous_sampled(&self) -> bool {
+ self.sampled_continuous
+ }
pub(super) fn volume_probe(&self) -> Option<VolumeProbe> {
self.volume.as_ref().map(|v| VolumeProbe {
source: v.source,
@@ -189,12 +208,15 @@ impl State {
Stage::Emitters => "emitters",
Stage::Resolve => "resolve",
Stage::Glass => "glass",
+ Stage::GlassSheet => "glass_sheet",
+ Stage::GlassLighting => "glass_lighting",
Stage::ShadowBeer => "shadow_beer",
Stage::ShadowGlass => "shadow_glass",
Stage::Effects => "effects",
Stage::Maps => "maps",
Stage::Aging => "aging",
Stage::Emission => "emission",
+ Stage::Caustics => "caustics",
Stage::Directional => "directional",
Stage::Punctual => "punctual",
Stage::Area => "area",
@@ -215,6 +237,15 @@ fn variates(task: &ImageTask, state: &State, domain: u64) -> job::Result<[f64; 2
fn continuing(task: &ImageTask, state: &State) -> job::Result<bool> {
Ok(state.depth + 1 < task.options.path.ok_or_else(|| invalid("CPU path settings disappeared"))?.max_depth)
}
+pub(super) fn advanced_normals(task: &ImageTask) -> bool {
+ // An HG collision adds phase transport inside the medium. Its closure does
+ // not use a boundary normal, so HG alone keeps the smooth interface policy.
+ task.options.caustics.is_some()
+ || task.options.dielectrics.iter().any(|input| input.model.is_some_and(|model| model.roughness > 0.0 || model.spectral()))
+}
+fn vertex_lighting(task: &ImageTask, state: &State) -> bool {
+ task.options.caustics.is_none() || !state.sampled_continuous
+}
fn shared<'a>(task: &'a ImageTask, state: &State) -> job::Result<super::super::prepared::SharedHit<'a>> {
let mut hit = unaged(task, state)?;
if let Some(aging) = task.aging.first() {
@@ -335,6 +366,9 @@ pub(super) fn step(task: &mut ImageTask) -> job::Result<()> {
result
}
fn advance(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
+ if state.stage == Stage::GlassLighting {
+ return glass_lighting::step(task, state);
+ }
if matches!(state.stage, Stage::Origin | Stage::MediumOrigin) {
let origin = state.origins.first_mut().ok_or_else(|| invalid("CPU primary-origin certificate missing"))?;
if origin.ready() {
@@ -595,6 +629,7 @@ fn advance(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
Stage::Glass => {
glass_one(task, state)?;
}
+ Stage::GlassSheet => advanced::sheet_step(task, state)?,
Stage::ShadowBeer => {
shadow_beer(task, state)?;
}
@@ -688,6 +723,17 @@ fn advance(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
super::super::lighting::validate_radiance(state.radiance).map_err(error)?;
} else {
state.light = 0;
+ state.caustic_gather = Default::default();
+ state.stage = if task.caustics.is_empty() { Stage::Directional } else { Stage::Caustics };
+ }
+ }
+ Stage::Caustics => {
+ let hit = shared(task, state)?;
+ let view = -state.ray.ok_or_else(|| invalid("CPU caustic receiver ray missing"))?.direction();
+ if let Some(contribution) = super::caustics::gather(task, &mut state.caustic_gather, hit, view)? {
+ state.radiance += multiply(state.throughput, contribution);
+ super::super::lighting::validate_radiance(state.radiance).map_err(error)?;
+ } else {
state.stage = Stage::Directional;
}
}
@@ -901,6 +947,7 @@ fn advance(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
state.throughput = multiply(state.throughput, sample.weight);
super::super::lighting::validate_radiance(state.throughput).map_err(error)?;
if state.throughput != Vec3::ZERO {
+ state.sampled_continuous = true;
state.previous_pdf = sample.pdf;
state.previous_position = hit.position;
if let Some(optical) = &mut state.optical {
@@ -928,7 +975,7 @@ fn advance(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
}
state.stage = Stage::Commit;
}
- Stage::Trace | Stage::Shadow | Stage::Commit | Stage::Origin | Stage::MediumOrigin => {
+ Stage::Trace | Stage::Shadow | Stage::Commit | Stage::Origin | Stage::MediumOrigin | Stage::GlassLighting => {
return Err(invalid("CPU path phase bypassed its continuation"));
}
}
@@ -944,6 +991,8 @@ struct GlassPath {
segment_start: Vec3,
source_plane: Option<[Vec3; 3]>,
collision: Option<scattering::Collision>,
+ spectral_channel: Option<u8>,
+ sheet: Option<advanced::SheetWalk>,
surface_range: Option<[usize; 2]>,
surface_forward: bool,
shadow_exact: bool,
@@ -1050,6 +1099,9 @@ fn glass_one(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
}
return Ok(());
};
+ if advanced::required(task, state, index)? {
+ return advanced::surface(task, state, index);
+ }
if !continuing(task, state)? {
state.stage = Stage::Commit;
return Ok(());
@@ -1060,8 +1112,12 @@ fn glass_one(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
let [draw, _] = variates(task, state, 0x4000)?;
let mut preserve_pdf = false;
let (outgoing, weight, entering) = if input.boundary == job::DielectricBoundary::ThinSheet {
- let (_, normal) = dielectric::shaded_interface(direction, normal, hit.shading_normal, 1.0, input.ior).map_err(error)?;
- let (interface, r, t) = dielectric::thin_sheet(direction, normal, input).map_err(error)?;
+ let normal = if advanced_normals(task) {
+ normal
+ } else {
+ dielectric::shaded_interface(direction, normal, hit.shading_normal, 1.0, input.ior).map_err(error)?.1
+ };
+ let (interface, r, t) = dielectric::modeled_sheet(direction, normal, input).map_err(error)?;
let p = thin_probability(r, t)?;
if draw < p {
(interface.reflected, r / p, None)
@@ -1097,7 +1153,11 @@ fn glass_one(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
};
let ni = ior(current)?;
let nt = ior(next)?;
- let (interface, _) = dielectric::shaded_interface(direction, normal, hit.shading_normal, ni, nt).map_err(error)?;
+ let interface = if advanced_normals(task) {
+ dielectric::interface(direction, normal, ni, nt).map_err(error)?
+ } else {
+ dielectric::shaded_interface(direction, normal, hit.shading_normal, ni, nt).map_err(error)?.0
+ };
if draw < interface.reflectance || interface.transmitted.is_none() {
(interface.reflected, Vec3::new(1.0, 1.0, 1.0), None)
} else {
@@ -1218,9 +1278,12 @@ fn shadow_glass(task: &ImageTask, state: &mut State) -> job::Result<()> {
if input.boundary != job::DielectricBoundary::ThinSheet {
return Err(invalid("CPU refractive closed-medium light connections require an unsupported caustic solver"));
}
- let (_, normal) =
- dielectric::shaded_interface(ray.direction(), hit.oriented_geometric_normal(), hit.shading_normal, 1.0, input.ior).map_err(error)?;
- let (_, r, t) = dielectric::thin_sheet(ray.direction(), normal, input).map_err(error)?;
+ let normal = if advanced_normals(task) {
+ hit.oriented_geometric_normal()
+ } else {
+ dielectric::shaded_interface(ray.direction(), hit.oriented_geometric_normal(), hit.shading_normal, 1.0, input.ior).map_err(error)?.1
+ };
+ let (_, r, t) = dielectric::modeled_sheet(ray.direction(), normal, input).map_err(error)?;
optical.shadow_probability *= 1.0 - thin_probability(r, t)?;
optical.shadow_interfaces = optical
.shadow_interfaces
diff --git a/crates/render/src/raytrace/image_scattering.rs b/crates/render/src/raytrace/image_scattering.rs
index 04e46d1cc9..df07adf036 100644
--- a/crates/render/src/raytrace/image_scattering.rs
+++ b/crates/render/src/raytrace/image_scattering.rs
@@ -105,7 +105,6 @@ fn scatter(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
let event = optical.collision.ok_or_else(|| invalid("CPU subsurface collision missing"))?;
let index = current(optical)?.ok_or_else(|| invalid("CPU subsurface collision lost its medium"))?;
let input = task.options.dielectrics.get(index).ok_or_else(|| invalid("CPU subsurface material missing"))?;
- let scattering = input.subsurface.filter(|s| s.active()).ok_or_else(|| invalid("CPU subsurface rate missing"))?;
let factor = dielectric::attenuation(input.absorption_per_mm, event.distance).map_err(error)?;
let throughput = multiply(state.throughput, factor);
super::super::super::lighting::validate_radiance(throughput).map_err(error)?;
@@ -116,20 +115,38 @@ fn scatter(task: &mut ImageTask, state: &mut State) -> job::Result<()> {
if state.depth == 0 {
task.primary_coverage = 1;
}
- if throughput == Vec3::ZERO || !continuing(task, state)? {
+ if throughput == Vec3::ZERO {
state.stage = Stage::Commit;
return Ok(());
}
let incoming = state.ray.ok_or_else(|| invalid("CPU subsurface incident ray missing"))?.direction();
+ if glass_lighting::begin(task, state, glass_lighting::Event::Medium { index, position: event.position, incoming }) {
+ return Ok(());
+ }
+ resume(task, state, index, event.position, incoming)
+}
+pub(super) fn resume(task: &ImageTask, state: &mut State, index: usize, position: Vec3, incoming: Vec3) -> job::Result<()> {
+ if !continuing(task, state)? {
+ state.stage = Stage::Commit;
+ return Ok(());
+ }
+ let scattering = task
+ .options
+ .dielectrics
+ .get(index)
+ .and_then(|input| input.subsurface)
+ .filter(|scattering| scattering.active())
+ .ok_or_else(|| invalid("CPU subsurface rate missing"))?;
let uniform = variates(task, state, 0x5001)?;
let direction = scattering.sample_direction(incoming, uniform).map_err(|e| JobError::new(ErrorCode::InvalidScene, e.to_string()))?;
- let ray = Ray::new(event.position, direction, 0.0_f64.next_up(), super::super::super::MAX_DISTANCE_MM).map_err(error)?;
+ let ray = Ray::new(position, direction, 0.0_f64.next_up(), super::super::super::MAX_DISTANCE_MM).map_err(error)?;
let optical = state.optical.as_mut().ok_or_else(|| invalid("CPU subsurface stack missing"))?;
- optical.segment_start = event.position;
+ optical.segment_start = position;
optical.source_plane = None;
optical.delta = true;
state.previous_pdf = 0.0;
- state.previous_position = event.position;
+ state.previous_position = position;
+ state.sampled_continuous = true;
state.ray = Some(ray);
state.cursor = Some(TraceCursor::new(ray, false));
state.hit = None;
diff --git a/crates/render/src/raytrace/image_tests.rs b/crates/render/src/raytrace/image_tests.rs
index a8d7981915..2f3598a948 100644
--- a/crates/render/src/raytrace/image_tests.rs
+++ b/crates/render/src/raytrace/image_tests.rs
@@ -1013,6 +1013,7 @@ fn dielectric_triangle_task(cancel: CancelToken) -> ImageTask {
let mut request = task.request;
let options = RaytraceOptions {
dielectrics: vec![job::DielectricOptions {
+ model: None,
shadow_transmission: false,
subsurface: None,
body_index: 0,
@@ -1129,6 +1130,7 @@ fn optical_sheet(name: &str, x: f64, z: f64) -> crate::ProductMesh {
fn optical_input(body_index: usize, body_name: &str, ior: f64) -> job::DielectricOptions {
job::DielectricOptions {
+ model: None,
shadow_transmission: false,
subsurface: None,
body_index,
@@ -1942,6 +1944,7 @@ fn cpu_denoise_production_guides_use_exact_body_and_material_bypass_policy() {
.iter()
.enumerate()
.map(|(body_index, body)| job::DielectricOptions {
+ model: None,
shadow_transmission: false,
subsurface: None,
body_index,
diff --git a/crates/render/src/raytrace/primary_aa_tests.rs b/crates/render/src/raytrace/primary_aa_tests.rs
index 687574ebef..7409bd6b98 100644
--- a/crates/render/src/raytrace/primary_aa_tests.rs
+++ b/crates/render/src/raytrace/primary_aa_tests.rs
@@ -747,6 +747,7 @@ fn complete_presentation(mut task: ImageTask, units: usize) -> PresentedOutput {
previews.push((samples_per_pixel, png));
}
ImagePoll::Complete(png) => {
+ assert_eq!(task.caustics.capacity(), 0, "completed presentation releases its prepaid photon map");
let master = task.take_linear_exr();
assert!(task.take_linear_exr().is_none(), "raw ownership transfers exactly once");
return (previews, png, master, task.work.used());
@@ -2192,6 +2193,7 @@ fn cpu_aging_limits_and_incompatible_authored_materials_refuse_without_dropping_
assert_eq!(options, before);
let mut options = original.options.clone();
options.dielectrics.push(job::DielectricOptions {
+ model: None,
shadow_transmission: false,
subsurface: None,
body_index: 0,
@@ -3485,6 +3487,7 @@ fn cpu_general_glass_fixture(samples: u32, nested: bool, ior: f64) -> ImageTask
.iter()
.enumerate()
.map(|(body_index, body)| job::DielectricOptions {
+ model: None,
body_index,
body_name: body.name.clone(),
boundary: job::DielectricBoundary::ClosedMesh,
@@ -3683,6 +3686,7 @@ fn cpu_glass_vertical_sheet_fixture(samples: u32, depth: u8) -> ImageTask {
scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.mesh.bounds()));
let mut options = base.options.clone();
options.dielectrics = vec![job::DielectricOptions {
+ model: None,
body_index: 1,
body_name: "Vertical sheet".into(),
boundary: job::DielectricBoundary::ThinSheet,
@@ -4316,6 +4320,44 @@ fn cpu_subsurface_fixture(samples: u32, nested: bool, endpoint: u8, depth: u8, r
let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() };
ImageTask::new(base.scene.clone(), request, CancelToken::default(), options).unwrap()
}
+#[test]
+fn cpu_subsurface_only_keeps_smooth_snell_direction_and_opt_in_caustics_keep_geometric_facets() {
+ let smooth = Vec3::new(0.28, 0.0, 0.96);
+ let incident = -Vec3::Z;
+ let eta = 2.0_f64 / 3.0;
+ let transmitted_cosine = (1.0 - (eta * smooth.x).powi(2)).sqrt();
+ let smooth_direction = incident * eta + smooth * (eta * smooth.z - transmitted_cosine);
+ assert!(smooth_direction.x < -0.09, "the smooth and geometric predictions must differ");
+ let seed = (0..256).find(|&seed| progressive::variates(seed, 0, 0, 0x5041_5448_4000)[0] > 0.2).unwrap();
+ for caustics in [false, true] {
+ let base = cpu_general_glass_fixture(1, false, 1.5);
+ let mut scene = base.scene.clone();
+ let mesh = Arc::make_mut(&mut scene.meshes[0].mesh);
+ mesh.normals = vec![smooth; mesh.positions.len()];
+ let mut options = base.options.clone();
+ options.path = Some(job::CpuPathOptions { max_depth: 2 });
+ options.progressive.as_mut().unwrap().seed = seed;
+ options.dielectrics[0].subsurface = Some(crate::transmission::subsurface::Subsurface { scattering_per_mm: 0.3, anisotropy: 0.4 });
+ options.caustics = caustics.then_some(job::CausticOptions { photons: 1, ..Default::default() });
+ let camera = crate::Camera { fov: 0.0, ..base.request.camera };
+ let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() };
+ let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap();
+ let mut transmitted = None;
+ for _ in 0..200_000 {
+ if let Some((1, ray, _)) = task.path.first().and_then(|path| path.surface_source()) {
+ // Observe the first refracted segment before HG free flight can
+ // replace its direction. Geometry still owns medium membership.
+ transmitted = Some(ray.direction());
+ break;
+ }
+ assert!(!matches!(task.step_with_previews(1).unwrap(), ImagePoll::Complete(_)));
+ }
+ let actual = transmitted.expect("fixture must trace the first transmitted segment");
+ let expected = if caustics { incident } else { smooth_direction };
+ assert!((actual - expected).len() < 1e-12, "caustics={caustics}: {actual:?} vs Snell direction {expected:?}");
+ }
+}
+
#[test]
fn cpu_subsurface_first_vertex_has_independent_analog_survival_and_physical_eye_pupil_beer() {
let samples = 64;
@@ -5928,3 +5970,732 @@ fn cpu_general_glass_prepared_cancel_and_work_exhaustion_keep_the_original_certi
assert!(task.encoder.is_none() && task.output.is_empty());
}
}
+
+#[test]
+fn cpu_path_tessellated_sheet_preserves_real_transmitted_visibility_film_and_raw_master() {
+ let fixture = || {
+ let original = cpu_glass_vertical_sheet_fixture(32, 8);
+ let mut scene = original.scene.clone();
+ let mut mesh = Mesh::default();
+ for y in 0..4 {
+ for z in 0..2 {
+ let y = -10.0 + f64::from(y) * 5.0;
+ let z = 1.0 + f64::from(z) * 2.0;
+ let begin = mesh.positions.len() as u32;
+ mesh.positions.extend([
+ Vec3::new(2.0, y, z),
+ Vec3::new(2.0, y, z + 2.0),
+ Vec3::new(2.0, y + 5.0, z + 2.0),
+ Vec3::new(2.0, y + 5.0, z),
+ ]);
+ mesh.triangles.extend([[begin, begin + 1, begin + 2], [begin, begin + 2, begin + 3]]);
+ }
+ }
+ scene.meshes[1].mesh = Arc::new(mesh);
+ ImageTask::new(scene, original.request.clone(), CancelToken::default(), original.options.clone()).unwrap()
+ };
+ let baseline = complete_presentation(cpu_glass_vertical_sheet_fixture(32, 8), 16384);
+ let actual = complete_presentation(fixture(), 1);
+ let batched = complete_presentation(fixture(), 16384);
+ assert_eq!(actual, batched, "worker quanta preserve every sheet checkpoint and raw bit");
+ assert_eq!(actual.0, baseline.0, "tessellation preserves the complete camera prefixes");
+ assert_eq!(actual.1, baseline.1, "tessellation preserves the final PNG");
+ assert_eq!(actual.2, baseline.2, "tessellation preserves the linear EXR");
+ assert!(actual.3 > baseline.3, "additional sheet proof and traversal are charged rather than hidden");
+}
+
+fn cpu_model_sheet_fixture(samples: u32, depth: u8, model: crate::glass_model::GlassModel, absorption: [f64; 3]) -> ImageTask {
+ let original = cpu_general_glass_fixture(samples, false, 1.5);
+ let mut scene = original.scene.clone();
+ scene.meshes[0].mesh = Arc::new(Mesh {
+ positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)],
+ triangles: vec![[0, 1, 2], [0, 2, 3]],
+ ..Default::default()
+ });
+ scene.bounds = scene.meshes[0].mesh.bounds();
+ let mut options = original.options.clone();
+ options.path = Some(job::CpuPathOptions { max_depth: depth });
+ options.dielectrics[0].boundary = job::DielectricBoundary::ThinSheet;
+ options.dielectrics[0].thickness_mm = 0.7;
+ options.dielectrics[0].absorption_per_mm = absorption;
+ options.dielectrics[0].model = Some(model);
+ let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() };
+ ImageTask::new(scene, request, CancelToken::default(), options).unwrap()
+}
+#[test]
+fn cpu_inactive_glass_model_preserves_every_original_prefix_master_and_work_unit() {
+ let original = cpu_general_glass_fixture(8, false, 1.5);
+ let mut options = original.options.clone();
+ options.dielectrics[0].model = Some(Default::default());
+ let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() };
+ let explicit = ImageTask::new(original.scene.clone(), request, CancelToken::default(), options).unwrap();
+ assert_eq!(complete_presentation(original, 1), complete_presentation(explicit, 16384));
+}
+#[test]
+fn cpu_spectral_sheet_rgb_furnace_has_unit_mass_and_real_film_response() {
+ use crate::glass_model::{Dispersion, GlassModel, ThinFilm};
+ let model = GlassModel {
+ roughness: 0.0,
+ dispersion: Some(Dispersion { abbe_number: 50.0 }),
+ thin_film: Some(ThinFilm { ior: 1.3, thickness_nm: 430.0 }),
+ };
+ let samples = 128;
+ // Independent normal-incidence Airy power quotient and lossless parallel
+ // slab series. No production Fresnel, Cauchy or sheet helper supplies the
+ // expected coefficients. The mean-RGB proposal has unit expected energy,
+ // but its finite R/p or T/(1-p) samples differ between colour channels.
+ let b = (0.5 / 50.0) / (486.1327_f64.powi(-2) - 656.2725_f64.powi(-2));
+ let reflected = [610.0_f64, 550.0, 460.0].map(|wavelength| {
+ let substrate = 1.5 + b * (wavelength.powi(-2) - 587.5618_f64.powi(-2));
+ let first = (1.0_f64 - 1.3) / (1.0 + 1.3);
+ let second = (1.3 - substrate) / (1.3 + substrate);
+ let cosine = (4.0 * std::f64::consts::PI * 1.3 * 430.0 / wavelength).cos();
+ let f = (first * first + second * second + 2.0 * first * second * cosine) / (1.0 + (first * second).powi(2) + 2.0 * first * second * cosine);
+ 2.0 * f / (1.0 + f)
+ });
+ let probability = reflected.into_iter().sum::<f64>() / 3.0;
+ let mut expected = [0.0; 3];
+ let mut reflection_count = 0;
+ for ordinal in 0..samples {
+ let reflect = progressive::variates(9, 0, ordinal, 0x5041_5448_4000)[0] < probability;
+ reflection_count += u32::from(reflect);
+ for (sum, r) in expected.iter_mut().zip(reflected) {
+ *sum += if reflect { r / probability } else { (1.0 - r) / (1.0 - probability) } / f64::from(samples);
+ }
+ }
+ assert!(reflection_count > 0 && reflection_count < samples, "both sheet branches need fixed-counter coverage");
+ for r in reflected {
+ let furnace = probability * (r / probability) + (1.0 - probability) * ((1.0 - r) / (1.0 - probability));
+ assert!((furnace - 1.0).abs() < 1e-14, "each wavelength has unit analytic expected furnace energy");
+ }
+ let (actual, _) = path_mean(cpu_model_sheet_fixture(samples, 4, model, [0.0; 3]));
+ for (actual, expected) in actual.into_iter().zip(expected) {
+ assert!((actual - expected).abs() < 1e-12, "finite RGB slab estimate {actual} vs independent Airy/counter estimate {expected}");
+ }
+ let coated = complete_presentation(cpu_model_sheet_fixture(32, 4, model, [0.2, 0.1, 0.0]), 1);
+ assert_eq!(coated, complete_presentation(cpu_model_sheet_fixture(32, 4, model, [0.2, 0.1, 0.0]), 16384));
+ let plain = complete_presentation(cpu_model_sheet_fixture(32, 4, GlassModel { thin_film: None, ..model }, [0.2, 0.1, 0.0]), 16384);
+ assert_ne!(coated.2, plain.2, "interference must reach actual linear transport rather than only request metadata");
+}
+#[test]
+fn cpu_rough_sheet_walk_consumes_virtual_interfaces_and_keeps_prefixes_raw_and_quanta_stable() {
+ let model = crate::glass_model::GlassModel { roughness: 0.4, ..Default::default() };
+ let shallow = path_mean(cpu_model_sheet_fixture(64, 2, model, [0.1, 0.2, 0.0])).0;
+ let deep = path_mean(cpu_model_sheet_fixture(64, 12, model, [0.1, 0.2, 0.0])).0;
+ assert!(deep.iter().all(|value| value.is_finite() && *value >= 0.0));
+ assert!(deep.into_iter().zip(shallow).all(|(deep, shallow)| deep >= shallow));
+ assert!(
+ deep.into_iter().zip(shallow).any(|(deep, shallow)| deep > shallow + 0.1),
+ "completed virtual exits add the transmitted rough-sheet paths"
+ );
+ let actual = complete_presentation(cpu_model_sheet_fixture(16, 12, model, [0.1, 0.2, 0.0]), 1);
+ assert_eq!(actual, complete_presentation(cpu_model_sheet_fixture(16, 12, model, [0.1, 0.2, 0.0]), 16384));
+ let smooth = complete_presentation(cpu_model_sheet_fixture(16, 12, Default::default(), [0.1, 0.2, 0.0]), 16384);
+ assert_ne!(actual.2, smooth.2, "frosted transport changes the actual film");
+}
+fn cpu_directional_caustic_fixture(photons: u32, radius_mm: f64) -> ImageTask {
+ let original = cpu_general_glass_fixture(1, false, 1.5);
+ let mut scene = original.scene.clone();
+ scene.meshes.push(ProductMesh {
+ name: "Caustic receiver".into(),
+ mesh: Arc::new(Mesh {
+ positions: vec![Vec3::new(-10.0, -10.0, 1.0), Vec3::new(10.0, -10.0, 1.0), Vec3::new(10.0, 10.0, 1.0), Vec3::new(-10.0, 10.0, 1.0)],
+ triangles: vec![[0, 1, 2], [0, 2, 3]],
+ ..Default::default()
+ }),
+ surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 0.0, 0.5, 1.0).unwrap()),
+ color: [255; 3],
+ opacity: 1.0,
+ faces: vec![],
+ transmission: None,
+ });
+ scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds()));
+ let mut options = original.options.clone();
+ options.path = Some(job::CpuPathOptions { max_depth: 1 });
+ options.dielectrics[0].absorption_per_mm = [0.0; 3];
+ options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]);
+ options.environment = Some(job::RaytraceEnvironmentOptions { color: [0.0; 3], intensity: 0.0 });
+ options.caustics = Some(job::CausticOptions { photons, radius_mm, max_depth: 8, seed: 81 });
+ let camera = crate::Camera {
+ target: Vec3::new(0.0, 0.0, 1.0),
+ distance: 0.5,
+ yaw: 0.0,
+ pitch: std::f64::consts::FRAC_PI_2,
+ roll: 0.0,
+ fov: 1e-6,
+ ..original.request.camera
+ };
+ let request = ImageRequest { camera, raytrace: Some(options.clone()), ..original.request.clone() };
+ ImageTask::new(scene, request, CancelToken::default(), options).unwrap()
+}
+#[test]
+fn cpu_delta_source_caustic_power_matches_independent_emission_counter_and_kernel_without_radiance_eta_loss() {
+ let photons = 4096;
+ let radius = 3.0;
+ let fixture = cpu_directional_caustic_fixture(photons, radius);
+ let bounds = fixture.scene.bounds;
+ let source_radius = (bounds.max - bounds.min).len() * 0.5;
+ let [dx, dy] = progressive::variates(9, 0, 0, 0);
+ let (origin, direction) = fixture.request.camera.ray(dx, dy, 1.0, 1.0);
+ let receiver = origin + direction * ((1.0 - origin.z) / direction.z);
+ let mut accepted = 0;
+ for ordinal in 0..photons {
+ let [u, v] = progressive::variates(81, 0, ordinal, 0x4341_5553_0001);
+ let r = source_radius * u.sqrt();
+ let position = Vec3::new(r * (std::f64::consts::TAU * v).cos(), r * (std::f64::consts::TAU * v).sin(), 1.0);
+ let branch = progressive::variates(81, 0, ordinal, 0x4341_5553_0002)[0];
+ if position.dist(receiver) <= radius && branch >= 0.04 {
+ accepted += 1;
+ }
+ }
+ assert!(accepted > 0);
+ // Each surviving photon carries irradiance*pi*source_radius²/N power;
+ // Lambert BRDF is1/pi and the disk kernel is1/(pi*radius²). Entry into
+ // n=1.5 retains power: a radiance eta² factor here would fail by2.25.
+ let expected = f64::from(accepted) * source_radius.powi(2) / (f64::from(photons) * std::f64::consts::PI * radius * radius);
+ let (actual, _) = path_mean(fixture);
+ for value in actual {
+ assert!((value - expected).abs() < 1e-10, "caustic {value} vs independent photon power {expected}");
+ }
+ let actual = complete_presentation(cpu_directional_caustic_fixture(512, radius), 1);
+ assert!(actual.1.starts_with(b"\x89PNG\r\n\x1a\n"));
+ assert!(actual.2.as_ref().is_some_and(|master| master.starts_with(b"\x76\x2f\x31\x01")));
+ assert_eq!(actual, complete_presentation(cpu_directional_caustic_fixture(512, radius), 16384));
+ let original = cpu_directional_caustic_fixture(512, radius);
+ let mut options = original.options.clone();
+ options.caustics = None;
+ let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() };
+ assert_eq!(
+ path_mean(ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap()).0,
+ [0.0; 3],
+ "ordinary delta NEE cannot sample the closed refractive connection"
+ );
+}
+#[test]
+fn cpu_caustic_prepass_is_prepaid_and_cancels_or_exhausts_before_any_image_commit() {
+ for cancel in [false, true] {
+ let mut task = cpu_directional_caustic_fixture(512, 3.0);
+ let mut entered = false;
+ for _ in 0..200_000 {
+ if task.bvh.is_some() && task.glass.first().is_some_and(|glass| glass.ready()) && task.caustics.first().is_some_and(|map| !map.ready()) {
+ entered = true;
+ break;
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ assert!(entered);
+ assert!(task.admission.preparation_bytes >= caustics::Task::required_bytes(task.options.caustics.unwrap()).unwrap());
+ let before = task.work.used();
+ if cancel {
+ task.cancel.cancel();
+ } else {
+ task.work.limit = before;
+ }
+ assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded });
+ assert_eq!(task.work.used(), before);
+ assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0);
+ assert!(task.take_linear_exr().is_none());
+ }
+}
+
+#[test]
+fn cpu_smooth_rgb_film_dispersion_sheet_keeps_transmitted_shadow_mis_and_inactive_identity() {
+ let fixture = |active: bool| {
+ let original = cpu_glass_vertical_sheet_fixture(16, 4);
+ let mut options = original.options.clone();
+ options.dielectrics[0].model = Some(if active {
+ crate::glass_model::GlassModel {
+ roughness: 0.0,
+ dispersion: Some(crate::glass_model::Dispersion { abbe_number: 45.0 }),
+ thin_film: Some(crate::glass_model::ThinFilm { ior: 1.3, thickness_nm: 430.0 }),
+ }
+ } else {
+ Default::default()
+ });
+ if active {
+ options.dielectrics[0].absorption_per_mm = [0.1, 0.2, 0.0];
+ options.dielectrics[0].thickness_mm = 0.7;
+ }
+ let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() };
+ ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap()
+ };
+ let legacy = complete_presentation(cpu_glass_vertical_sheet_fixture(16, 4), 1);
+ assert_eq!(legacy, complete_presentation(fixture(false), 16384));
+ let active = complete_presentation(fixture(true), 1);
+ assert_eq!(active, complete_presentation(fixture(true), 16384));
+ assert_ne!(active.2, legacy.2, "the spectral slab affects actual transmitted-light connections and BSDF chains");
+ let raw = native_exr_pixels(active.2.as_deref().unwrap());
+ assert!(raw.pixels().all(|pixel| pixel.0.iter().all(|value| value.is_finite() && *value >= 0.0)));
+}
+#[test]
+fn cpu_photon_prepass_respects_an_analytic_emitter_before_the_opaque_receiver() {
+ let original = cpu_directional_caustic_fixture(512, 3.0);
+ let mut options = original.options.clone();
+ options.area_lights = Some(vec![job::RectangleLightOptions {
+ center_mm: [0.0, 0.0, 1.75],
+ edge_u_mm: [18.0, 0.0, 0.0],
+ edge_v_mm: [0.0, 18.0, 0.0],
+ color: [1.0; 3],
+ intensity: 0.0,
+ }]);
+ let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() };
+ assert_eq!(
+ path_mean(ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap()).0,
+ [0.0; 3],
+ "nonradiant analytic area geometry still blocks source photons before the receiver"
+ );
+}
+#[test]
+fn cpu_point_source_inside_certified_glass_keeps_initial_medium_and_adds_reflected_caustic_power() {
+ let fixture = |caustics: bool| {
+ let original = cpu_directional_caustic_fixture(1024, 3.0);
+ let mut options = original.options.clone();
+ options.lights = Some(vec![]);
+ options.punctual_lights = Some(vec![job::PunctualLightOptions {
+ position_mm: [0.0, 0.0, 1.5],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: None,
+ }]);
+ if !caustics {
+ options.caustics = None;
+ }
+ let request = ImageRequest { raytrace: Some(options.clone()), ..original.request.clone() };
+ ImageTask::new(original.scene, request, CancelToken::default(), options).unwrap()
+ };
+ let baseline = path_mean(fixture(false)).0;
+ let actual = path_mean(fixture(true)).0;
+ assert!(
+ actual.into_iter().zip(baseline).all(|(actual, baseline)| actual > baseline),
+ "inside-source initialization must preserve upward photons reflected by the closed boundary; direct paths are already covered by NEE"
+ );
+}
+
+fn cpu_hard_rough_fixture(samples: u32, depth: u8, sheet: bool, roughness: f64, light: [f64; 3]) -> ImageTask {
+ let model = crate::glass_model::GlassModel { roughness, ..Default::default() };
+ let base = if sheet { cpu_model_sheet_fixture(samples, depth, model, [0.0; 3]) } else { cpu_general_glass_fixture(samples, false, 1.5) };
+ let mut options = base.options.clone();
+ options.path = Some(job::CpuPathOptions { max_depth: depth });
+ options.dielectrics[0].model = Some(model);
+ options.dielectrics[0].absorption_per_mm = [0.0; 3];
+ options.lights = Some(vec![job::DirectionalLightOptions { direction: light, color: [1.0; 3], intensity: 1.0 }]);
+ options.environment = Some(job::RaytraceEnvironmentOptions { color: [0.0; 3], intensity: 0.0 });
+ let camera = crate::Camera {
+ target: Vec3::new(0.0, 0.0, if sheet { 0.0 } else { 2.0 }),
+ distance: 0.5,
+ yaw: 0.0,
+ pitch: std::f64::consts::FRAC_PI_2,
+ roll: 0.0,
+ fov: 1e-9,
+ ..base.request.camera
+ };
+ let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() };
+ ImageTask::new(base.scene, request, CancelToken::default(), options).unwrap()
+}
+fn cpu_reconfigure(base: ImageTask, change: impl FnOnce(&mut RaytraceOptions)) -> ImageTask {
+ let mut options = base.options.clone();
+ change(&mut options);
+ let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() };
+ ImageTask::new(base.scene, request, CancelToken::default(), options).unwrap()
+}
+fn assert_rgb_close(actual: [f64; 3], expected: [f64; 3], tolerance: f64) {
+ for (a, e) in actual.into_iter().zip(expected) {
+ assert!((a - e).abs() <= tolerance, "linear radiance {a} vs independent expected {e}");
+ }
+}
+#[test]
+fn cpu_rough_hard_source_reflection_has_independent_normal_ggx_measure_at_the_last_vertex() {
+ // At normal incidence, D=1/(pi*r^4), G=1 and F=((1-1.5)/(1+1.5))^2=.04.
+ // A hard source contributes f*cos(theta), without a light-selection PDF.
+ for sheet in [false, true] {
+ for roughness in [0.4_f64, 0.7, 1.0] {
+ let expected = 0.04 / (4.0 * std::f64::consts::PI * roughness.powi(4));
+ assert_rgb_close(path_mean(cpu_hard_rough_fixture(4, 1, sheet, roughness, [0.0, 0.0, 1.0])).0, [expected; 3], 1e-12);
+ }
+ for spot in [false, true] {
+ let base = cpu_hard_rough_fixture(4, 1, sheet, 0.5, [0.0, 0.0, 1.0]);
+ let z = if sheet { 2.0 } else { 4.0 };
+ let point = cpu_reconfigure(base, |options| {
+ options.lights = Some(vec![]);
+ options.punctual_lights = Some(vec![job::PunctualLightOptions {
+ position_mm: [0.0, 0.0, z],
+ color: [1.0; 3],
+ intensity: 2.0,
+ reference_distance_mm: 3.0,
+ minimum_distance_mm: 0.001,
+ cone: spot.then_some(job::SpotConeOptions {
+ emitted_axis: [0.0, 0.0, -1.0],
+ inner_half_angle_radians: 0.2,
+ outer_half_angle_radians: 0.4,
+ }),
+ }]);
+ });
+ let expected = 0.04 / (4.0 * std::f64::consts::PI * 0.5_f64.powi(4)) * 2.0 * 9.0 / 4.0;
+ assert_rgb_close(path_mean(point).0, [expected; 3], 1e-10);
+ }
+ }
+}
+#[test]
+fn cpu_inside_point_and_spot_rough_transmission_apply_physical_beer_and_hg_survival() {
+ for spot in [false, true] {
+ let fixture = cpu_reconfigure(cpu_hard_rough_fixture(4, 1, false, 0.5, [0.0, 0.0, -1.0]), |options| {
+ options.lights = Some(vec![]);
+ options.dielectrics[0].absorption_per_mm = [0.2, 0.4, 0.0];
+ options.dielectrics[0].subsurface = Some(crate::transmission::subsurface::Subsurface { scattering_per_mm: 0.3, anisotropy: 0.4 });
+ options.punctual_lights = Some(vec![job::PunctualLightOptions {
+ position_mm: [0.0, 0.0, 1.0],
+ color: [1.0; 3],
+ intensity: 1.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: spot.then_some(job::SpotConeOptions {
+ emitted_axis: [0.0, 0.0, 1.0],
+ inner_half_angle_radians: 0.2,
+ outer_half_angle_radians: 0.4,
+ }),
+ }]);
+ });
+ // Normal Walter radiance BTDF: (1-F)*D*ni^2/(ni-nt)^2.
+ // The source is exactly1mm into the transmitted-side medium. Visibility
+ // excludes its endpoint by one ULP; attenuation still uses the full mm.
+ let btdf = 0.96 / (std::f64::consts::PI * 0.5_f64.powi(4) * 0.5_f64.powi(2));
+ assert_rgb_close(path_mean(fixture).0, [0.2_f64, 0.4, 0.0].map(|a| btdf * (-(a + 0.3)).exp()), 1e-9);
+ }
+}
+#[test]
+fn cpu_rough_direct_lighting_survives_a_null_sampled_continuation() {
+ let seed = (0..4096)
+ .find(|seed| {
+ let [branch, u] = progressive::variates(*seed, 0, 0, 0x5041_5448_4000);
+ branch < 0.02 && u > 0.75
+ })
+ .expect("fixed counter covers a reflected visible facet below the macro horizon");
+ for sheet in [false, true] {
+ let mut task = cpu_reconfigure(cpu_hard_rough_fixture(1, 2, sheet, 1.0, [0.0, 0.0, 1.0]), |o| o.progressive.as_mut().unwrap().seed = seed);
+ let mut null_commit = false;
+ for _ in 0..200_000 {
+ if let Some(state) = task.path.first()
+ && state.stage_name() == "commit"
+ {
+ assert_eq!(state.medium_probe().unwrap().depth, 0, "the sampled continuation is actually null at the first interface");
+ null_commit = true;
+ break;
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ assert!(null_commit);
+ assert_rgb_close(path_mean(task).0, [0.04 / (4.0 * std::f64::consts::PI); 3], 1e-12);
+ }
+}
+fn cpu_backlit_rough_fixture(depth: u8, sheet: bool, map: bool, photons: u32) -> ImageTask {
+ cpu_reconfigure(cpu_hard_rough_fixture(32, depth, sheet, 0.4, [0.0, 0.0, -1.0]), |options| {
+ options.caustics = map.then_some(job::CausticOptions { photons, radius_mm: 3.0, max_depth: 2, seed: 81 });
+ })
+}
+#[test]
+fn cpu_rough_receiver_reservoir_finalizes_at_depth_and_camera_partition_has_one_first_continuous_receiver() {
+ for sheet in [false, true] {
+ let map_one = path_mean(cpu_backlit_rough_fixture(1, sheet, true, 1024)).0;
+ let map_two = path_mean(cpu_backlit_rough_fixture(2, sheet, true, 1024)).0;
+ assert_eq!(map_one, map_two, "a sampled rough continuation must not count a second photon/NEE receiver");
+ assert!(map_one.into_iter().all(|value| value > 0.0), "the reservoir retains the terminal second-interface rough receiver");
+ assert_eq!(path_mean(cpu_backlit_rough_fixture(1, sheet, false, 1024)).0, [0.0; 3]);
+ assert!(
+ path_mean(cpu_backlit_rough_fixture(2, sheet, false, 1024)).0.into_iter().all(|value| value > 0.0),
+ "without the map, the last-depth internal escape connection contributes"
+ );
+ }
+ let fixture = || cpu_reconfigure(cpu_backlit_rough_fixture(2, true, true, 256), |o| o.progressive.as_mut().unwrap().samples_per_pixel = 4);
+ assert_eq!(
+ complete_presentation(fixture(), 1),
+ complete_presentation(fixture(), 16384),
+ "reservoir, gather and NEE keep every prefix, raw bit and charged work unit across quanta"
+ );
+}
+#[test]
+fn cpu_internal_rough_sheet_direct_survives_a_later_null_interface_sample() {
+ let mut found = false;
+ for seed in 0..256 {
+ let mut task = cpu_reconfigure(cpu_hard_rough_fixture(1, 3, true, 1.0, [0.0, 0.0, -1.0]), |o| o.progressive.as_mut().unwrap().seed = seed);
+ let mut retained = None;
+ for _ in 0..50_000 {
+ if let Some(state) = task.path.first() {
+ if let Some((1, 3, pending, radiance)) = state.hard_light_probe()
+ && pending.x > 0.0
+ {
+ retained = Some(radiance + pending);
+ }
+ if state.stage_name() == "commit" {
+ if state.medium_probe().unwrap().depth == 1
+ && let Some(expected) = retained
+ {
+ assert_rgb_close(path_mean(task).0, [expected.x, expected.y, expected.z], 1e-12);
+ found = true;
+ }
+ break;
+ }
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ if found {
+ break;
+ }
+ }
+ assert!(found, "fixed counter search must exercise positive internal lighting followed by a null microfacet continuation");
+}
+#[test]
+fn cpu_hard_glass_lighting_is_cooperative_and_cancellable_before_any_film_commit() {
+ for cancel in [false, true] {
+ let mut task = cpu_hard_rough_fixture(4, 1, false, 0.5, [0.0, 0.0, 1.0]);
+ let mut entered = false;
+ for _ in 0..200_000 {
+ if task.path.first().is_some_and(|state| state.stage_name() == "glass_lighting") {
+ entered = true;
+ break;
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ assert!(entered);
+ let before = task.work.used();
+ if cancel {
+ task.cancel.cancel();
+ } else {
+ task.work.limit = before;
+ }
+ assert_eq!(task.step_with_previews(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded });
+ assert_eq!(task.work.used(), before);
+ assert_eq!(task.progressive.as_ref().unwrap().film.samples(), 0);
+ assert!(task.take_linear_exr().is_none());
+ }
+}
+#[test]
+fn cpu_selected_hg_hard_point_and_spot_nee_match_independent_collision_phase_and_extinction() {
+ let samples = 64;
+ for spot in [false, true] {
+ let base = cpu_subsurface_fixture(samples, false, 0, 1, [0.8, 0.0], 0.4, None);
+ let mut options = base.options.clone();
+ options.dielectrics[0].absorption_per_mm = [0.2, 0.4, 0.0];
+ options.environment = Some(job::RaytraceEnvironmentOptions { color: [0.0; 3], intensity: 0.0 });
+ options.punctual_lights = Some(vec![job::PunctualLightOptions {
+ position_mm: [1.0, 0.0, 1.0],
+ color: [1.0; 3],
+ intensity: 2.0,
+ reference_distance_mm: 1.0,
+ minimum_distance_mm: 0.001,
+ cone: spot.then_some(job::SpotConeOptions {
+ emitted_axis: [-1.0, 0.0, -0.3],
+ inner_half_angle_radians: 0.1,
+ outer_half_angle_radians: 1.1,
+ }),
+ }]);
+ let camera = crate::Camera { fov: 1e-9, ..base.request.camera };
+ let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() };
+ let mut expected = [0.0; 3];
+ let mut collisions = 0;
+ for ordinal in 0..samples {
+ let [x, y] = progressive::variates(9, 0, ordinal, 0);
+ let (origin, direction) = camera.ray(x, y, 1.0, 1.0);
+ let u = progressive::variates(9, 0, ordinal, 0x5041_5448_5000)[0];
+ let travel = -(1.0 - u).ln() / 0.8;
+ if travel >= -origin.z / direction.z {
+ continue;
+ }
+ collisions += 1;
+ let point = origin + direction * travel;
+ let delta = Vec3::new(1.0, 0.0, 1.0) - point;
+ let distance = delta.len();
+ let toward_source = delta / distance;
+ let cosine = direction.dot(toward_source);
+ let phase = (1.0 - 0.4_f64.powi(2)) / (4.0 * std::f64::consts::PI * (1.0 + 0.4_f64.powi(2) - 0.8 * cosine).powf(1.5));
+ let cone = if spot {
+ let axis = Vec3::new(-1.0, 0.0, -0.3);
+ let cosine = (-toward_source).dot(axis / axis.len());
+ let t = ((cosine - 1.1_f64.cos()) / (0.1_f64.cos() - 1.1_f64.cos())).clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+ } else {
+ 1.0
+ };
+ for (sum, absorption) in expected.iter_mut().zip([0.2_f64, 0.4, 0.0]) {
+ *sum += phase * 2.0 * cone / distance.powi(2) * (-absorption * (travel + distance) - 0.8 * distance).exp() / f64::from(samples);
+ }
+ }
+ assert!(collisions > 0 && collisions < samples);
+ assert_rgb_close(path_mean(ImageTask::new(base.scene, request, CancelToken::default(), options).unwrap()).0, expected, 1e-12);
+ }
+}
+#[test]
+fn cpu_hg_photon_reservoir_reaches_volume_receivers_after_a_closed_optical_event() {
+ let fixture = |map: bool| {
+ let base = cpu_subsurface_fixture(64, false, 0, 1, [0.8, 0.0], 0.4, None);
+ cpu_reconfigure(base, |options| {
+ options.dielectrics[0].absorption_per_mm = [0.0; 3];
+ options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]);
+ options.environment = Some(job::RaytraceEnvironmentOptions { color: [0.0; 3], intensity: 0.0 });
+ options.caustics = map.then_some(job::CausticOptions { photons: 1024, radius_mm: 3.0, max_depth: 4, seed: 81 });
+ })
+ };
+ assert_eq!(path_mean(fixture(false)).0, [0.0; 3], "a straight delta connection cannot cross the closed optical boundary");
+ let mut task = fixture(true);
+ for _ in 0..1_000_000 {
+ if task.caustics.first().is_some_and(|map| map.ready()) {
+ break;
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ let counts = task.caustics.first().unwrap().receiver_counts();
+ assert!(counts[2] > 0, "selected HG collisions must be actual photon receivers");
+ assert!(counts.into_iter().sum::<usize>() <= 1024, "one reservoir record at most per launched light path");
+ assert!(path_mean(task).0.into_iter().all(|value| value > 0.0));
+}
+#[test]
+fn cpu_matched_index_coated_rough_delta_transmission_keeps_the_first_continuous_photon_receiver() {
+ let base = cpu_backlit_rough_fixture(3, false, true, 1024);
+ let mut scene = base.scene.clone();
+ let mut upper = dielectric::tests::box_body(0.5);
+ upper.name = "Matched coated upper glass".into();
+ for position in &mut Arc::make_mut(&mut upper.mesh).positions {
+ position.z += 2.5;
+ }
+ scene.meshes.push(upper);
+ scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds()));
+ let mut options = base.options.clone();
+ options.progressive.as_mut().unwrap().samples_per_pixel = 64;
+ let mut upper_input = options.dielectrics[0].clone();
+ upper_input.body_index = 1;
+ upper_input.body_name = scene.meshes[1].name.clone();
+ upper_input.ior = 1.0;
+ upper_input.model = Some(crate::glass_model::GlassModel {
+ roughness: 0.7,
+ thin_film: Some(crate::glass_model::ThinFilm { ior: 1.3, thickness_nm: 250.0 }),
+ dispersion: None,
+ });
+ options.dielectrics.push(upper_input);
+ let camera = crate::Camera { target: Vec3::new(0.0, 0.0, 3.0), ..base.request.camera };
+ let request = ImageRequest { camera, raytrace: Some(options.clone()), ..base.request.clone() };
+ let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap();
+ let mut reached = false;
+ for _ in 0..1_000_000 {
+ if let Some(state) = task.path.first()
+ && let Some((2, _, hit)) = state.surface_source()
+ && task.looks[hit.primitive_index].body_index == 0
+ {
+ assert!(!state.continuous_sampled(), "both coated matched-index transmissions are delta events despite authored roughness");
+ reached = true;
+ break;
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ assert!(reached);
+ assert!(path_mean(task).0.into_iter().all(|value| value > 0.0), "a later rough receiver still gathers after a chain of actual delta samples");
+}
+#[test]
+fn cpu_rough_hard_visibility_crosses_a_smooth_sheet_and_keeps_earlier_analytic_occlusion() {
+ let fixture = |sheet: bool, blocker: bool| {
+ let base = cpu_hard_rough_fixture(4, 1, false, 0.5, [0.2, 0.0, 1.0]);
+ let mut scene = base.scene.clone();
+ let mut options = base.options.clone();
+ if sheet {
+ let mut body = scene.meshes[0].clone();
+ body.name = "Smooth optical visibility sheet".into();
+ body.mesh = Arc::new(Mesh {
+ positions: vec![Vec3::new(-10.0, -10.0, 3.5), Vec3::new(10.0, -10.0, 3.5), Vec3::new(10.0, 10.0, 3.5), Vec3::new(-10.0, 10.0, 3.5)],
+ triangles: vec![[0, 1, 2], [0, 2, 3]],
+ ..Default::default()
+ });
+ let mut input = options.dielectrics[0].clone();
+ input.body_index = 1;
+ input.body_name = body.name.clone();
+ input.boundary = job::DielectricBoundary::ThinSheet;
+ input.model = None;
+ input.thickness_mm = 0.2;
+ input.shadow_transmission = true;
+ options.dielectrics.push(input);
+ scene.meshes.push(body);
+ }
+ if blocker {
+ options.area_lights = Some(vec![job::RectangleLightOptions {
+ center_mm: [0.0, 0.0, 3.0],
+ edge_u_mm: [18.0, 0.0, 0.0],
+ edge_v_mm: [0.0, -18.0, 0.0],
+ color: [1.0; 3],
+ intensity: 0.0,
+ }]);
+ }
+ scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds()));
+ let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() };
+ ImageTask::new(scene, request, CancelToken::default(), options).unwrap()
+ };
+ let bare = path_mean(fixture(false, false)).0;
+ let cosine = 1.0 / 1.04_f64.sqrt();
+ let transmitted_cosine = (1.0 - (1.0 - cosine * cosine) / 2.25).sqrt();
+ let rs = ((cosine - 1.5 * transmitted_cosine) / (cosine + 1.5 * transmitted_cosine)).powi(2);
+ let rp = ((1.5 * cosine - transmitted_cosine) / (1.5 * cosine + transmitted_cosine)).powi(2);
+ // Internal bounces retain their polarization. Sum each independent
+ // lossless slab series before averaging the two incident polarizations.
+ let transmission = 0.5 * ((1.0 - rs) / (1.0 + rs) + (1.0 - rp) / (1.0 + rp));
+ assert_rgb_close(path_mean(fixture(true, false)).0, bare.map(|value| value * transmission), 1e-12);
+ assert_eq!(
+ path_mean(fixture(true, true)).0,
+ [0.0; 3],
+ "the area before the transmitted sheet remains inside the original physical visibility segment"
+ );
+}
+#[test]
+fn cpu_photon_multi_receiver_reservoir_keeps_one_record_and_has_an_independent_finite_counter_power_oracle() {
+ let base = cpu_directional_caustic_fixture(4096, 3.0);
+ let mut scene = base.scene.clone();
+ scene.meshes[0] = dielectric::tests::box_body(1.0);
+ for p in &mut Arc::make_mut(&mut scene.meshes[0].mesh).positions {
+ p.z += 4.0;
+ }
+ let mut lower = dielectric::tests::box_body(1.0);
+ lower.name = "Lower matched rough glass".into();
+ for p in &mut Arc::make_mut(&mut lower.mesh).positions {
+ p.z += 2.0;
+ }
+ scene.meshes.push(lower);
+ scene.bounds = scene.meshes.iter().fold(Aabb3::EMPTY, |bounds, body| bounds.union(&body.mesh.bounds()));
+ let mut options = base.options.clone();
+ options.caustics.as_mut().unwrap().max_depth = 5;
+ options.dielectrics[0].body_name = scene.meshes[0].name.clone();
+ options.dielectrics[0].ior = 1.0;
+ options.dielectrics[0].model = Some(crate::glass_model::GlassModel { roughness: 0.4, ..Default::default() });
+ let mut second = options.dielectrics[0].clone();
+ second.body_index = 2;
+ second.body_name = scene.meshes[2].name.clone();
+ options.dielectrics.push(second);
+ let request = ImageRequest { raytrace: Some(options.clone()), ..base.request.clone() };
+ let mut task = ImageTask::new(scene, request, CancelToken::default(), options).unwrap();
+ let [x, y] = progressive::variates(9, 0, 0, 0);
+ let (origin, direction) = task.request.camera.ray(x, y, 1.0, 1.0);
+ let receiver = origin + direction * ((1.0 - origin.z) / direction.z);
+ let source_radius = (task.scene.bounds.max - task.scene.bounds.min).len() * 0.5;
+ let mut accepted = 0;
+ for ordinal in 0..4096 {
+ let [u, v] = progressive::variates(81, 0, ordinal, 0x4341_5553_0001);
+ let r = source_radius * u.sqrt();
+ let position = Vec3::new(r * (std::f64::consts::TAU * v).cos(), r * (std::f64::consts::TAU * v).sin(), 1.0);
+ // All four interfaces have equal indices: straight, unit power, no
+ // resampling or Fresnel loss. The first optical event is ineligible;
+ // exit/entry/exit/opaque are exactly four candidate receiver visits.
+ // The last independent reservoir draw alone decides opaque retention.
+ let retain_opaque = progressive::variates(81, 0, ordinal, 0x4341_5553_0000 + 4 * 256 + 13)[0] < 0.25;
+ if position.dist(receiver) <= 3.0 && retain_opaque {
+ accepted += 1;
+ }
+ }
+ assert!(accepted > 0);
+ for _ in 0..2_000_000 {
+ if task.caustics.first().is_some_and(|map| map.ready()) {
+ break;
+ }
+ task.step_with_previews(1).unwrap();
+ }
+ let counts = task.caustics.first().unwrap().receiver_counts();
+ assert!(counts[0] > 0 && counts[1] > 0, "the same bounded map stores both opaque and optical visits");
+ assert!(counts.into_iter().sum::<usize>() <= 4096);
+ let expected = 4.0 * f64::from(accepted) * source_radius.powi(2) / (4096.0 * std::f64::consts::PI * 9.0);
+ assert_rgb_close(path_mean(task).0, [expected; 3], 1e-10);
+}
diff --git a/crates/render/src/transmission.rs b/crates/render/src/transmission.rs
index 895df0376a..4a89b9aedd 100644
--- a/crates/render/src/transmission.rs
+++ b/crates/render/src/transmission.rs
@@ -9,6 +9,7 @@ use crate::surface::{SurfaceError, unit_direction};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Transmission {
+ model: Option<crate::glass_model::GlassModel>,
absorption_per_mm: Vec3,
thin_wall_thickness_mm: Option<f64>,
shadow_transmission: bool,
@@ -17,6 +18,7 @@ pub struct Transmission {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransmissionError {
+ Model,
Absorption,
Scattering,
Distance,
@@ -28,6 +30,7 @@ pub enum TransmissionError {
impl std::fmt::Display for TransmissionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
+ Self::Model => "glass model requires finite bounded roughness, dispersion and optical film parameters",
Self::Scattering => "subsurface scattering requires a closed medium, finite scattering 0..100/mm, HG anisotropy -0.95..0.95 and disabled straight shadow transmission",
Self::Absorption => "absorption_per_mm must be finite RGB coefficients in [0, 100] per mm",
Self::Distance => "geometric absorption distance must be finite and nonnegative",
@@ -50,7 +53,15 @@ impl Transmission {
if thin_wall_thickness_mm.is_some_and(|v| !v.is_finite() || !(0.0..=10000.0).contains(&v)) {
return Err(TransmissionError::Thickness);
}
- Ok(Self { absorption_per_mm, thin_wall_thickness_mm, shadow_transmission: thin_wall_thickness_mm.is_some(), subsurface: None })
+ Ok(Self { model: None, absorption_per_mm, thin_wall_thickness_mm, shadow_transmission: thin_wall_thickness_mm.is_some(), subsurface: None })
+ }
+ pub fn with_model(mut self, model: crate::glass_model::GlassModel) -> Result<Self, TransmissionError> {
+ model.validate(1.5).map_err(|_| TransmissionError::Model)?;
+ self.model = Some(model);
+ Ok(self)
+ }
+ pub fn model(self) -> Option<crate::glass_model::GlassModel> {
+ self.model
}
/// Thin sheets enable straight shadow transmission by default; solids opt in.
pub fn with_shadow_transmission(mut self, enabled: bool) -> Self {
@@ -130,7 +141,11 @@ pub fn refract(incident: Vec3, normal: Vec3, incident_ior: f64, transmitted_ior:
if cosine < 0.0 {
return Err(TransmissionError::Direction);
}
- let f = fresnel(cosine.min(1.0), incident_ior, transmitted_ior)?;
+ let cosine = cosine.min(1.0);
+ let f = fresnel(cosine, incident_ior, transmitted_ior)?;
+ if incident_ior == transmitted_ior {
+ return Ok(Some(d));
+ }
Ok(f.transmitted_cosine.map(|ct| {
let eta = incident_ior / transmitted_ior;
d * eta + n * (eta * cosine - ct)
@@ -150,10 +165,19 @@ pub fn slab(
return Err(TransmissionError::Thickness);
}
let f = fresnel(cosine, outside_ior, inside_ior)?;
- let Some(ct) = f.transmitted_cosine.filter(|v| *v > 0.0) else {
+ let Some(ct) = f.transmitted_cosine else {
return Ok((Vec3::new(1.0, 1.0, 1.0), Vec3::ZERO));
};
- let a = transmission.attenuation(thickness_mm / ct)?;
+ // A zero-thickness sheet has zero optical distance, including matched-index
+ // exact grazing. Positive thickness without a crossing has no finite path.
+ let distance = if thickness_mm == 0.0 {
+ 0.0
+ } else if ct > 0.0 {
+ thickness_mm / ct
+ } else {
+ return Err(TransmissionError::Angle);
+ };
+ let a = transmission.attenuation(distance)?;
let channel = |r: f64, a: f64| {
let denominator = 1.0 - r * r * a * a;
if denominator <= 0.0 {
diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs
index cfcba4d8fa..2458cca11d 100644
--- a/crates/ui-egui/src/render_workspace.rs
+++ b/crates/ui-egui/src/render_workspace.rs
@@ -1311,6 +1311,9 @@ fn switch_celestial_method(app: &mut SolveApp, method: ImageMethod, enable_indir
if next.studio.volume.is_some_and(|volume| volume.active()) {
return Err(app.tr("render.cpu_volume_path_required").into());
}
+ if next.studio.caustics.is_some() {
+ return Err(app.tr("render.caustics_path_required").into());
+ }
if celestial_switch_active(app) {
return Err(app.tr("render.cpu_celestial_switch").into());
}
@@ -1384,7 +1387,7 @@ fn select_image_method(app: &mut SolveApp, method: ImageMethod) {
if method != app.render_workspace.view.method
&& method != ImageMethod::Raster
&& app.render_workspace.view.method != ImageMethod::Raster
- && (celestial_switch_active(app) || app.render_workspace.view.studio.volume.is_some())
+ && (celestial_switch_active(app) || app.render_workspace.view.studio.volume.is_some() || app.render_workspace.view.studio.caustics.is_some())
{
let result = if app.render_workspace.view.studio.volume.is_some() {
switch_volume_method(app, method, false)
@@ -1428,7 +1431,8 @@ fn method_selector(app: &mut SolveApp, ui: &mut egui::Ui) {
fn method_dropdown(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response {
let current = app.render_workspace.view.method;
let label = app.tr(current.label()).to_string();
- let bounded = celestial_switch_active(app) || app.render_workspace.view.studio.volume.is_some();
+ let bounded =
+ celestial_switch_active(app) || app.render_workspace.view.studio.volume.is_some() || app.render_workspace.view.studio.caustics.is_some();
let width = ui.available_width().min(crate::theme::Tokens::get().form_card_width);
let choices = |ui: &mut egui::Ui| {
for (method, handle) in [
@@ -1449,7 +1453,10 @@ fn method_dropdown(app: &mut SolveApp, ui: &mut egui::Ui) -> egui::Response {
}
}
let volume_path = app.render_workspace.view.studio.volume.is_some_and(|volume| volume.active());
- if current == ImageMethod::GpuRaytrace && (celestial_switch_active(app) || volume_path) && app.render_workspace.view.raytrace.path.is_none() {
+ if current == ImageMethod::GpuRaytrace
+ && (celestial_switch_active(app) || volume_path || app.render_workspace.view.studio.caustics.is_some())
+ && app.render_workspace.view.raytrace.path.is_none()
+ {
let sampling = app.render_workspace.view.raytrace.progressive.unwrap_or_default();
let detail = crate::i18n::format(
if volume_path { "render.cpu_volume_enable_path_plan" } else { "render.cpu_celestial_adopt" },
diff --git a/crates/ui-egui/src/render_workspace_cpu.rs b/crates/ui-egui/src/render_workspace_cpu.rs
index c9ebe03c45..9b456efcc9 100644
--- a/crates/ui-egui/src/render_workspace_cpu.rs
+++ b/crates/ui-egui/src/render_workspace_cpu.rs
@@ -491,6 +491,7 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> {
options.sun = app.render_workspace.view.studio.sun_enabled.then(|| Box::new(app.render_workspace.view.studio.sun));
options.sky = None;
options.volume = app.render_workspace.view.studio.volume;
+ options.caustics = app.render_workspace.view.studio.caustics;
options.output = super::studio::cpu_output(&app.render_workspace.view);
options.adaptive = app.render_workspace.view.studio.adaptive.map(Box::new);
options.denoise = app.render_workspace.view.studio.denoise;
diff --git a/crates/ui-egui/src/render_workspace_materials.rs b/crates/ui-egui/src/render_workspace_materials.rs
index f2a93fb846..07282f84d0 100644
--- a/crates/ui-egui/src/render_workspace_materials.rs
+++ b/crates/ui-egui/src/render_workspace_materials.rs
@@ -51,6 +51,7 @@ impl Boundary {
#[derive(Clone, Debug)]
pub(super) struct Glass {
+ pub model: Option<solidcraft_engine::render::glass_model::GlassModel>,
pub recipe: Option<&'static str>,
pub ior: f64,
pub absorption: [f64; 3],
@@ -61,7 +62,16 @@ pub(super) struct Glass {
}
impl Default for Glass {
fn default() -> Self {
- Self { recipe: None, ior: 1.5, absorption: [0.0; 3], boundary: Boundary::Closed, thickness: 1.0, shadows: false, subsurface: None }
+ Self {
+ model: None,
+ recipe: None,
+ ior: 1.5,
+ absorption: [0.0; 3],
+ boundary: Boundary::Closed,
+ thickness: 1.0,
+ shadows: false,
+ subsurface: None,
+ }
}
}
impl Glass {
@@ -74,6 +84,7 @@ impl Glass {
GlassBoundary::Closed => (Boundary::Closed, 1.0),
};
Ok(Self {
+ model: None,
subsurface: None,
recipe: Some(preset.id),
ior: recipe.dielectric_ior,
@@ -164,6 +175,7 @@ impl Binding {
binding.saved_source = Some(optics);
binding.glass_enabled = true;
binding.glass = Glass {
+ model: optics.model,
recipe: None,
ior: optics.ior,
absorption: optics.absorption_per_mm,
@@ -200,6 +212,7 @@ impl Binding {
}
fn optics(&self) -> solidcraft_engine::doc::render_optics::OpticalMaterial {
solidcraft_engine::doc::render_optics::OpticalMaterial {
+ model: self.glass.model,
ior: self.glass.ior,
absorption_per_mm: self.glass.absorption,
boundary: match self.glass.boundary {
@@ -526,6 +539,10 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> {
wire["boundary"] = json!(value.boundary.wire());
wire["thickness_mm"] = json!(if value.boundary == Boundary::Thin { value.thickness } else { 0.0 });
wire["shadow_transmission"] = json!(value.shadows);
+ if let Some(model) = value.model {
+ model.validate(value.ior).map_err(|e| e.to_string())?;
+ wire["model"] = json!(model);
+ }
if let Some(subsurface) = value.subsurface {
Transmission::new(Vec3::new(r, g, b), (value.boundary == Boundary::Thin).then_some(value.thickness))
.map_err(|e| e.to_string())?
@@ -737,6 +754,7 @@ fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding)
let glass = &mut binding.glass;
let mut changed = false;
ui.add_enabled_ui(binding.glass_enabled, |ui| {
+ changed |= advanced_glass_controls(app, ui, glass);
let mut boundary = match glass.boundary {
Boundary::Closed => 0,
Boundary::Thin => 1,
@@ -829,6 +847,57 @@ fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding)
note(app, ui, if cpu { "render.cpu_material_certification" } else { "render.material_certification" });
}
+fn advanced_glass_controls(app: &SolveApp, ui: &mut egui::Ui, glass: &mut Glass) -> bool {
+ use solidcraft_engine::render::glass_model::{Dispersion, GlassModel, ThinFilm};
+ let before = glass.model;
+ let mut enabled = before.is_some();
+ let toggle = ui_kit::checkbox(ui, app.tr("render.glass_model_enable"), &mut enabled);
+ crate::scenario::publish_target("render:glass:model-enable", toggle.rect);
+ if toggle.changed() {
+ glass.model = enabled.then(GlassModel::default);
+ }
+ if let Some(model) = &mut glass.model {
+ ui_kit::row(ui, app.tr("render.glass_roughness"), |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut model.roughness, 0.0..=1.0, 0.01, "");
+ crate::scenario::publish_target("render:glass:roughness", field.rect);
+ field
+ });
+ let mut dispersion = model.dispersion.is_some();
+ let toggle = ui_kit::checkbox(ui, app.tr("render.glass_dispersion"), &mut dispersion);
+ crate::scenario::publish_target("render:glass:dispersion-enable", toggle.rect);
+ if toggle.changed() {
+ model.dispersion = dispersion.then_some(Dispersion { abbe_number: 50.0 });
+ }
+ if let Some(dispersion) = &mut model.dispersion {
+ ui_kit::row(ui, app.tr("render.glass_abbe"), |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut dispersion.abbe_number, 5.0..=200.0, 0.5, "");
+ crate::scenario::publish_target("render:glass:abbe", field.rect);
+ field
+ });
+ }
+ let mut film = model.thin_film.is_some();
+ let toggle = ui_kit::checkbox(ui, app.tr("render.glass_film"), &mut film);
+ crate::scenario::publish_target("render:glass:film-enable", toggle.rect);
+ if toggle.changed() {
+ model.thin_film = film.then_some(ThinFilm { ior: 1.35, thickness_nm: 400.0 });
+ }
+ if let Some(film) = &mut model.thin_film {
+ ui_kit::row(ui, app.tr("render.glass_film_ior"), |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut film.ior, 1.0..=3.0, 0.01, "");
+ crate::scenario::publish_target("render:glass:film-ior", field.rect);
+ field
+ });
+ ui_kit::row(ui, app.tr("render.glass_film_thickness"), |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut film.thickness_nm, 0.0..=100000.0, 1.0, " nm");
+ crate::scenario::publish_target("render:glass:film-thickness", field.rect);
+ field
+ });
+ }
+ ui_kit::text(ui, app.tr("render.glass_model_help"), ui_kit::Text::Note("render.glass_model_help"));
+ }
+ before != glass.model
+}
+
fn coat_controls(app: &mut SolveApp, ui: &mut egui::Ui, binding: &mut Binding) -> bool {
let enabled = ui_kit::checkbox(ui, app.tr("render.material_coat_enable"), &mut binding.coat_enabled);
crate::scenario::publish_target("render:coat:enable", enabled.rect);
@@ -1176,7 +1245,7 @@ fn save_optics(app: &mut SolveApp, binding: &Binding) -> Result<(), String> {
setup.camera = saved.camera;
}
let optics = json!({"ior":value.ior,"absorption_per_mm":value.absorption,"boundary":value.boundary.wire(),
- "thickness_mm":if value.boundary==Boundary::Thin {value.thickness} else {0.0},"shadow_transmission":value.shadows,"subsurface":value.subsurface});
+ "thickness_mm":if value.boundary==Boundary::Thin {value.thickness} else {0.0},"shadow_transmission":value.shadows,"subsurface":value.subsurface,"model":value.model});
app.run(
"render.optics.bind",
json!({"name":name,"set":setup,"body_index":binding.target.ordinal,"body_name":binding.target.name,
diff --git a/crates/ui-egui/src/render_workspace_setups.rs b/crates/ui-egui/src/render_workspace_setups.rs
index eec0e151f0..12d0ee4797 100644
--- a/crates/ui-egui/src/render_workspace_setups.rs
+++ b/crates/ui-egui/src/render_workspace_setups.rs
@@ -108,6 +108,7 @@ pub(super) fn draft(app: &SolveApp) -> Result<RenderSetup, String> {
RenderJob::CpuRaytrace {
transparent_background: view.transparent,
options: Box::new(CpuJob {
+ caustics: view.studio.caustics,
volume: view.studio.volume,
sun: view.studio.sun_enabled.then_some(view.studio.sun),
sky: (view.cpu.environment == cpu::Environment::Sky).then_some(SkyEnvironment::Sky {
@@ -154,6 +155,7 @@ pub(super) fn draft(app: &SolveApp) -> Result<RenderSetup, String> {
RenderJob::GpuPath {
transparent_background: view.transparent,
options: Box::new(GpuJob {
+ caustics: studio.caustics,
samples: view.samples,
max_depth: view.max_depth,
seed: view.seed,
@@ -323,7 +325,9 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) {
view.studio.sun = sun;
view.studio.lighting_enabled = true;
}
+ view.studio.caustics = options.caustics;
view.raytrace = RaytraceOptions {
+ caustics: options.caustics,
sun: options.sun.map(Box::new),
volume: options.volume,
adaptive: options.adaptive.map(Box::new),
@@ -380,6 +384,7 @@ fn load_values(view: &mut super::ViewState, setup: RenderSetup) {
view.max_depth = options.max_depth;
view.seed = options.seed;
view.studio.aging = options.aging.clone();
+ view.studio.caustics = options.caustics;
view.studio.nested_media = options.nested_media;
view.studio.volume = options.volume;
view.studio.adaptive = options.adaptive;
@@ -568,6 +573,7 @@ pub(super) fn sync_revision(app: &mut SolveApp) {
raytrace.output,
raytrace.lens,
raytrace.path,
+ raytrace.caustics,
raytrace.sun,
raytrace.sky,
raytrace.volume,
@@ -589,6 +595,7 @@ pub(super) fn sync_revision(app: &mut SolveApp) {
cpu.samples,
studio.aging,
studio.nested_media,
+ studio.caustics,
studio.volume,
studio.adaptive,
studio.transmission_samples,
diff --git a/crates/ui-egui/src/render_workspace_studio.rs b/crates/ui-egui/src/render_workspace_studio.rs
index 2ff7637a53..77c538a0b2 100644
--- a/crates/ui-egui/src/render_workspace_studio.rs
+++ b/crates/ui-egui/src/render_workspace_studio.rs
@@ -16,6 +16,7 @@ pub(super) enum Environment {
#[derive(Clone, Debug)]
pub(super) struct View {
+ pub caustics: Option<solidcraft_engine::render::job::CausticOptions>,
pub aging: solidcraft_engine::doc::render_aging::SavedAgingStack,
pub nested_media: bool,
pub volume: Option<solidcraft_engine::render::job::volume::HomogeneousVolume>,
@@ -48,6 +49,7 @@ pub(super) struct View {
impl Default for View {
fn default() -> Self {
Self {
+ caustics: None,
aging: Default::default(),
nested_media: false,
volume: None,
@@ -100,6 +102,7 @@ pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> {
params["linear_exr"] = json!(view.linear_exr);
params["aging"] = json!(view.aging);
params["nested_media"] = json!(view.nested_media);
+ params["caustics"] = json!(view.caustics);
params["volume"] = json!(view.volume);
params["adaptive"] = json!(view.adaptive);
params["transmission_samples"] = json!(view.transmission_samples);
diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs
index 48ac0bdd69..97e46748d4 100644
--- a/crates/ui-egui/src/render_workspace_tests.rs
+++ b/crates/ui-egui/src/render_workspace_tests.rs
@@ -3722,6 +3722,7 @@ fn clicked_setup_save_reload_and_switch_keep_gpu_numeric_intent_without_a_host()
job: Some(RenderJob::GpuPath {
transparent_background: true,
options: Box::new(GpuJob {
+ caustics: None,
aging: Default::default(),
nested_media: true,
volume: Some(solidcraft_engine::render::job::volume::HomogeneousVolume { extinction_per_mm: 0.0, ..Default::default() }),
@@ -15453,3 +15454,273 @@ fn classic_results_and_comparison_keep_their_reserved_chrome_and_scale_policy()
}
}
}
+
+fn advanced_glass_saved_fixture(method: ImageMethod) -> Harness {
+ use solidcraft_engine::render::glass_model::{Dispersion, GlassModel, ThinFilm};
+ let mut h = stable_glass_draft_fixture(method, true);
+ let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "Glass A").unwrap();
+ let mut optics = h.app.session.doc.render.setups["Studio"].optics.iter().next().unwrap().optics;
+ optics.model = Some(GlassModel {
+ roughness: 0.21,
+ dispersion: Some(Dispersion { abbe_number: 57.0 }),
+ thin_film: Some(ThinFilm { ior: 1.37, thickness_nm: 263.0 }),
+ });
+ // Authored inactive scattering is independent of the interface model and
+ // must survive an edit to just one optical field.
+ optics.subsurface = Some(solidcraft_engine::render::transmission::subsurface::Subsurface { scattering_per_mm: 0.0, anisotropy: 0.42 });
+ h.app
+ .run(
+ "render.optics.bind",
+ json!({"name":"Studio","body_index":target.ordinal,"body_name":target.name,
+ "expected_revision":h.app.session.revision,"replace":true,"optics":optics}),
+ )
+ .unwrap();
+ setups::load(&mut h.app);
+ h.app.render_workspace.view.live_paused = true;
+ h
+}
+
+#[test]
+fn advanced_glass_lens_save_preserves_caustic_job_drafts_and_refuses_unsaved_optics_atomically() {
+ use solidcraft_engine::doc::render_settings::RenderJob;
+ use solidcraft_engine::render::job::{CausticOptions, CpuProgressiveOptions, ThinLens};
+ for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] {
+ let mut h = advanced_glass_saved_fixture(method);
+ let saved = h.app.session.doc.render.setups["Studio"].clone();
+ let quality = CausticOptions { photons: 8192, radius_mm: 0.125, max_depth: 11, seed: 901 };
+ h.app.render_workspace.view.studio.caustics = Some(quality);
+ if method == ImageMethod::CpuRaytrace {
+ h.app.render_workspace.view.raytrace.progressive = Some(CpuProgressiveOptions { samples_per_pixel: 7, seed: 93 });
+ } else {
+ h.app.render_workspace.view.samples = 7;
+ h.app.render_workspace.view.seed = 93;
+ }
+ h.app.cam.yaw += 0.125;
+ setups::refresh_dirty(&mut h.app);
+ let live_camera = h.app.cam;
+ let before = h.app.session.doc.clone();
+ let model = h.app.session.model.state();
+ let undo = h.app.session.undo.len();
+ let mut expected_saved = saved.clone();
+ let mut expected_draft = setups::draft(&h.app).unwrap();
+ assert_ne!(expected_draft.job, saved.job, "the fixture must carry independent caustic quality and sampling drafts");
+ let lens = ThinLens { aperture_radius_mm: 0.05, focus_distance_mm: 80.0 };
+ for setup in [&mut expected_saved, &mut expected_draft] {
+ match setup.job.as_mut().unwrap() {
+ RenderJob::CpuRaytrace { options, .. } => options.lens = Some(lens),
+ RenderJob::GpuPath { options, .. } => options.lens = Some(lens),
+ RenderJob::Raster { .. } => panic!("the fixture requires an image job"),
+ }
+ }
+ shot::set_lens(&mut h.app, "Studio", Some(lens)).unwrap();
+ assert_eq!(h.app.session.doc.render.setups["Studio"], expected_saved, "lens Save must preserve every saved advanced optical and job value");
+ assert_eq!(setups::draft(&h.app).unwrap(), expected_draft, "independent caustic quality and sampling must remain in the unsaved draft");
+ assert_eq!(image_request(&h.app).unwrap()["settings"], json!(expected_draft));
+ assert!(h.app.render_workspace.view.dirty);
+ assert_eq!(h.app.cam, live_camera);
+ assert_eq!(h.app.session.doc.render.setups["Studio"].optics, saved.optics);
+ assert!(Arc::ptr_eq(&model, &h.app.session.model.state()));
+ assert_eq!(h.app.session.undo.len(), undo + 1);
+ assert!(h.app.render_workspace.view.job.is_none());
+ h.app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(h.app.session.doc, before);
+ assert_eq!(h.app.cam, live_camera);
+ h.app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(h.app.session.doc.render.setups["Studio"], expected_saved);
+ assert_eq!(h.app.cam, live_camera);
+
+ let mut h = advanced_glass_saved_fixture(method);
+ let source = h.app.session.doc.render.setups["Studio"].optics.iter().next().unwrap().optics;
+ let target = materials::read_targets(&mut h.app).unwrap().into_iter().find(|target| target.name == "Glass A").unwrap();
+ let mut binding = materials::Binding::from_saved(target, &h.app, source);
+ binding.glass.model.as_mut().unwrap().roughness = 0.43;
+ h.app.render_workspace.view.materials.enabled = true;
+ h.app.render_workspace.view.materials.bindings.push(binding);
+ h.app.render_workspace.view.studio.caustics = Some(quality);
+ let before = h.app.session.doc.clone();
+ let model = h.app.session.model.state();
+ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len());
+ let camera = h.app.cam;
+ let request = image_request(&h.app).unwrap();
+ let error = shot::set_lens(&mut h.app, "Studio", Some(lens)).unwrap_err();
+ assert!(error.contains(h.app.tr("render.setup_runtime_unsupported")), "an unreviewed optical override must refuse a lens Save");
+ assert!(Arc::ptr_eq(&before, &h.app.session.doc));
+ assert!(Arc::ptr_eq(&model, &h.app.session.model.state()));
+ assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history);
+ assert_eq!(h.app.cam, camera);
+ assert_eq!(image_request(&h.app).unwrap(), request, "a refused lens Save must preserve the complete optical and caustic draft");
+ assert!(h.app.render_workspace.view.materials.bindings[0].has_unsaved_optics_intent());
+ }
+}
+
+#[test]
+fn advanced_glass_pointer_edit_keeps_saved_dispersion_film_and_independent_optics_through_native_reopen() {
+ use solidcraft_engine::doc::render_optics::SavedOptics;
+ for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] {
+ let mut h = advanced_glass_saved_fixture(method);
+ h.app.run("select.set", json!({"items":[solidcraft_engine::Sel::Body{name:"Glass A".into()}]})).unwrap();
+ let selected = object_selection(&h.app);
+ selection_editor(&mut h.app, &selected);
+ h.app.run("view.render_stage", json!({"stage":"look"})).unwrap();
+ h.frames(3);
+ let document = h.app.session.doc.clone();
+ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len());
+ let saved = document.render.setups["Studio"].clone();
+ let original = saved.optics.iter().next().unwrap().clone();
+ assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "opening a saved row must not create an unsaved material override");
+ assert_eq!(image_request(&h.app).unwrap()["settings"], json!(saved), "opening the advanced editor must preserve the complete saved setup");
+ stable_glass_draft_click(&mut h, &format!("dialog:section:{}", crate::i18n::tr("render.appearance_editor.glass")));
+ stable_glass_draft_reveal(&mut h, "render:glass:roughness");
+ let field = crate::scenario::rect_of("render:glass:roughness").unwrap();
+ assert!(stable_glass_draft_viewport(&h).contains_rect(field));
+ h.step(&json!({"click":[field.center().x,field.center().y],"double":true})).unwrap();
+ h.step(&json!({"key":"A","cmd":true})).unwrap();
+ h.step(&json!({"text":"0.43"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ h.frames(2);
+ let mut changed = original.optics;
+ changed.model.as_mut().unwrap().roughness = 0.43;
+ let binding = h.app.render_workspace.view.materials.bindings.iter().find(|binding| binding.target.name == "Glass A").unwrap();
+ assert_eq!(binding.glass.model, changed.model, "a roughness edit must retain the hydrated dispersion and film values");
+ assert!(binding.has_unsaved_optics_intent());
+ let mut expected = saved.clone();
+ expected.optics.set(SavedOptics { target: original.target.clone(), optics: changed }, true).unwrap();
+ let request = image_request(&h.app).unwrap();
+ assert_eq!(request["settings"], json!(expected), "changing roughness must preserve saved camera/lens, maps, coat, absorption and scattering");
+ assert!(request.pointer("/raytrace/dielectrics").is_none(), "a stable advanced edit must keep its stable target lane");
+ setups::refresh_dirty(&mut h.app);
+ assert!(h.app.render_workspace.view.dirty);
+ assert!(Arc::ptr_eq(&document, &h.app.session.doc));
+ assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history);
+ stable_glass_draft_click(&mut h, &format!("dialog:section:{}", crate::i18n::tr("render.appearance_editor.saved")));
+ h.step(&json!({"widget":h.app.tr("render.appearance_editor.replace")})).unwrap();
+ stable_glass_draft_click(&mut h, "render:optics-save");
+ assert_eq!(
+ h.app.session.doc.render.setups["Studio"], expected,
+ "the real saved-optics button must commit the prospective model exactly once"
+ );
+ assert_eq!(h.app.session.undo.len(), history.1 + 1);
+ assert_eq!(h.app.session.doc.features, document.features);
+ assert_eq!(h.app.session.doc.materials, document.materials);
+ assert_eq!(h.app.session.doc.appearances, document.appearances);
+ let path = h.dir.join(format!("advanced-glass-{method:?}.solidcraft"));
+ h.app.run("file.save", json!({"path":path})).unwrap();
+ h.app.run("doc.open", json!({"path":path})).unwrap();
+ assert_eq!(h.app.session.doc.render.setups["Studio"], expected, "actual native save/open retains the advanced stable assignment");
+ h.app.render_workspace.view.name = "Studio".into();
+ enter(&mut h.app, true).unwrap();
+ setups::load(&mut h.app);
+ h.app.render_workspace.view.live_paused = true;
+ assert_eq!(image_request(&h.app).unwrap()["settings"], json!(expected));
+ assert!(h.app.render_workspace.view.materials.bindings.is_empty(), "native hydration must not create an unsaved material override");
+ }
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn advanced_glass_live_request_host(h: &mut Harness, method: ImageMethod) -> bool {
+ use solidcraft_engine::render::{RenderFeature, job};
+ if method == ImageMethod::CpuRaytrace {
+ let host = job::CpuHost::for_platform().unwrap();
+ h.app.session.set_render_job_host(Some(host.clone())).unwrap();
+ h.app.render_workspace.image_host = Some(host);
+ return image_host(&h.app, method).is_ok();
+ }
+ struct RequestOnly;
+ impl job::ImageExecutor for RequestOnly {
+ fn supports_glass_models(&self) -> bool {
+ true
+ }
+ fn supports_caustics(&self) -> bool {
+ true
+ }
+ fn descriptor(&self) -> job::Result<ExecutorDescriptor> {
+ let mut descriptor = job::CpuHost::cooperative().descriptor()?;
+ descriptor.id = ExecutorId::new("ui-request-only").unwrap();
+ descriptor.profiles[0].features.push(RenderFeature::Progressive);
+ Ok(descriptor)
+ }
+ fn admit(&self, _: &ProductScene, _: &job::ImageRequest, _: job::JobOptions) -> job::Result<job::Admission> {
+ Err(job::JobError::new(job::ErrorCode::HostUnavailable, "paused UI request test does not render"))
+ }
+ fn begin(&self, _: ProductScene, _: job::ImageRequest, _: job::JobOptions, _: job::CancelToken) -> job::Result<Box<dyn job::ImageWork>> {
+ Err(job::JobError::new(job::ErrorCode::HostUnavailable, "paused UI request test does not render"))
+ }
+ }
+ h.app.render_workspace.path_host = PathHost::Ready(job::ImageHost::with_executor(Arc::new(RequestOnly)).unwrap());
+ true
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn caustic_quality_survives_cpu_gpu_ui_save_load_and_changes_the_paused_live_request_identity() {
+ use solidcraft_engine::render::job::CausticOptions;
+ for method in [ImageMethod::CpuRaytrace, ImageMethod::GpuRaytrace] {
+ let mut h = advanced_glass_saved_fixture(method);
+ let can_observe_live = advanced_glass_live_request_host(&mut h, method);
+ h.app.preferences.render_legacy_image_defaults = false;
+ h.app.viewport.rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(256.0, 192.0)));
+ h.app.render_workspace.view.live_paused = true;
+ let saved = h.app.session.doc.render.setups["Studio"].clone();
+ let document = h.app.session.doc.clone();
+ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len());
+ let quality = CausticOptions { photons: 8192, radius_mm: 0.125, max_depth: 11, seed: 901 };
+ h.app.render_workspace.view.studio.caustics = Some(quality);
+ setups::refresh_dirty(&mut h.app);
+ assert!(h.app.render_workspace.view.dirty, "the clean-shot fingerprint includes explicit caustic quality");
+ let request = image_request(&h.app).unwrap();
+ assert_eq!(request["settings"]["job"]["options"]["caustics"], json!(quality));
+ assert_eq!(request["settings"]["optics"], json!(saved.optics));
+ let mut runtime = json!({});
+ if method == ImageMethod::CpuRaytrace {
+ cpu::params(&h.app, &mut runtime).unwrap();
+ assert_eq!(runtime["raytrace"]["caustics"], json!(quality), "CPU temporary request capture retains all four quality controls");
+ } else {
+ studio::params(&h.app, &mut runtime).unwrap();
+ assert_eq!(runtime["caustics"], json!(quality), "GPU temporary request capture retains all four quality controls");
+ }
+ if can_observe_live {
+ live::advance(&mut h.app, &h.ctx, 100.0);
+ let first = live::inspect(&h.app);
+ assert_eq!(first["request"]["settings"]["job"]["options"]["caustics"], json!(quality));
+ let mut changed = quality;
+ changed.radius_mm = 0.25;
+ h.app.render_workspace.view.studio.caustics = Some(changed);
+ live::advance(&mut h.app, &h.ctx, 101.0);
+ let next = live::inspect(&h.app);
+ assert!(
+ next["generation"].as_u64().unwrap() > first["generation"].as_u64().unwrap(),
+ "a radius edit invalidates the previous live request identity"
+ );
+ assert_eq!(next["request"]["settings"]["job"]["options"]["caustics"], json!(changed));
+ assert_eq!(next["request"]["settings"]["optics"], json!(saved.optics));
+ assert_eq!(next["pending"], false);
+ assert_eq!(next["running"], false, "inspecting paused live intent must not submit a render");
+ h.app.render_workspace.view.studio.caustics = Some(quality);
+ }
+ assert!(Arc::ptr_eq(&document, &h.app.session.doc));
+ assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len()), history);
+ setups::save(&mut h.app).unwrap();
+ let expected = h.app.session.doc.render.setups["Studio"].clone();
+ assert_eq!(image_request(&h.app).unwrap()["settings"], json!(expected));
+ h.app.render_workspace.view.studio.caustics = None;
+ setups::refresh_dirty(&mut h.app);
+ assert!(h.app.render_workspace.view.dirty);
+ setups::load(&mut h.app);
+ assert_eq!(h.app.render_workspace.view.studio.caustics, Some(quality));
+ assert!(!h.app.render_workspace.view.dirty);
+ if method == ImageMethod::CpuRaytrace {
+ assert_eq!(h.app.render_workspace.view.raytrace.caustics, Some(quality));
+ }
+ let path = h.dir.join(format!("caustic-quality-{method:?}.solidcraft"));
+ h.app.run("file.save", json!({"path":path})).unwrap();
+ h.app.run("doc.open", json!({"path":path})).unwrap();
+ assert_eq!(h.app.session.doc.render.setups["Studio"], expected);
+ h.app.render_workspace.view.name = "Studio".into();
+ enter(&mut h.app, true).unwrap();
+ setups::load(&mut h.app);
+ h.app.render_workspace.view.live_paused = true;
+ assert_eq!(h.app.render_workspace.view.studio.caustics, Some(quality));
+ assert_eq!(image_request(&h.app).unwrap()["settings"], json!(expected));
+ assert!(h.app.render_workspace.view.job.is_none());
+ }
+}
diff --git a/crates/ui-egui/src/render_workspace_transport.rs b/crates/ui-egui/src/render_workspace_transport.rs
index 3fef525eec..e2375d3dd7 100644
--- a/crates/ui-egui/src/render_workspace_transport.rs
+++ b/crates/ui-egui/src/render_workspace_transport.rs
@@ -56,6 +56,7 @@ pub(super) fn adaptive_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
app.render_workspace.view.dirty |= before != app.render_workspace.view.studio.adaptive;
}
pub(super) fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
+ caustics_controls(app, ui);
if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace {
cpu_glass_controls(app, ui);
return;
@@ -83,6 +84,46 @@ pub(super) fn glass_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
before != (app.render_workspace.view.studio.nested_media, app.render_workspace.view.studio.transmission_samples);
}
+fn caustics_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
+ let before = app.render_workspace.view.studio.caustics;
+ let mut enabled = before.is_some();
+ let can_enable = app.render_workspace.view.method == super::ImageMethod::GpuRaytrace
+ || (app.render_workspace.view.method == super::ImageMethod::CpuRaytrace && app.render_workspace.view.raytrace.path.is_some());
+ let response = ui.add_enabled_ui(enabled || can_enable, |ui| ui_kit::checkbox(ui, app.tr("render.caustics_enable"), &mut enabled));
+ crate::scenario::publish_target("render:caustics:enable", response.inner.rect);
+ if response.inner.changed() {
+ app.render_workspace.view.studio.caustics = enabled.then(solidcraft_engine::render::job::CausticOptions::default);
+ }
+ if let Some(options) = &mut app.render_workspace.view.studio.caustics {
+ let photons = crate::i18n::tr("render.caustics_photons");
+ ui_kit::row(ui, photons, |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut options.photons, 1..=65536, 64.0, "");
+ crate::scenario::publish_target("render:caustics:photons", field.rect);
+ field
+ });
+ let radius = crate::i18n::tr("render.caustics_radius");
+ ui_kit::row(ui, radius, |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut options.radius_mm, 1e-6..=1e6, 0.1, " mm");
+ crate::scenario::publish_target("render:caustics:radius", field.rect);
+ field
+ });
+ let seed = crate::i18n::tr("render.children.seed");
+ ui_kit::row(ui, seed, |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut options.seed, 0..=u32::MAX, 1.0, "");
+ crate::scenario::publish_target("render:caustics:seed", field.rect);
+ field
+ });
+ let depth = crate::i18n::tr("render.caustics_depth");
+ ui_kit::row(ui, depth, |ui| {
+ let field = ui_kit::number_field_preserving(ui, &mut options.max_depth, 1..=16, 1.0, "");
+ crate::scenario::publish_target("render:caustics:depth", field.rect);
+ field
+ });
+ }
+ ui_kit::text(ui, app.tr("render.caustics_help"), ui_kit::Text::Note("render.caustics_help"));
+ app.render_workspace.view.dirty |= before != app.render_workspace.view.studio.caustics;
+}
+
/// CPU has one progressive Fresnel event per film ordinal. GPU strata and its
/// nested-media flag are deliberately absent from this method's controls.
fn cpu_glass_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md
index 7d2637d0b2..8ae060be1e 100644
--- a/docs/book/src/reference/glossary.md
+++ b/docs/book/src/reference/glossary.md
@@ -33,6 +33,13 @@ later pull requests, one topic at a time, each pointing at its entry here.
## Terms
+### abbe number
+
+Number measuring optical dispersion as `(nd - 1) / (nF - nC)` at the Fraunhofer d, F and C wavelengths.
+
+- **In SolidCraft:** Glass `model.dispersion.abbe_number`; larger values give less chromatic dispersion.
+- **For translators:** an optical material quantity, not a sample or photon count.
+
### appearance
How a body, face or component looks on screen and in renders.
@@ -107,6 +114,18 @@ a tree.
it (in French, *arborescence*), so that "browser" and "web browser" don't share a word. See
*web browser*.
+### caustic
+
+A concentration or structured redistribution of light caused by reflection or refraction.
+
+- **In SolidCraft:** Render job `caustics` controls the photon estimate for point and hard directional sources; finite sources also have camera-path estimates.
+
+### chromatic dispersion
+
+Variation of refractive index with wavelength that can separate colours along refracted paths.
+
+- **In SolidCraft:** Glass `model.dispersion`; the current renderer uses three representative wavelength bands.
+
### component
A named container of bodies, sketches, construction geometry and other components that can be
@@ -246,6 +265,12 @@ makes is a *group*.
- **Elsewhere:** folder, node.
- **For translators:** not a group and not a folder on disk.
+### gather radius
+
+Radius of the surface neighbourhood used to estimate illumination from nearby photon hits.
+
+- **In SolidCraft:** Caustics `radius_mm`; smaller values preserve sharper details and require more photons to reduce noise.
+
### group
A named container that someone makes, in the browser or in the timeline, to keep items together.
@@ -445,6 +470,12 @@ a standard size.
- **Elsewhere:** standard part, library part, fastener, catalogue part.
- **For translators:** see *Words with more than one meaning*, "part".
+### thin-film interference
+
+Interference between coherent optical waves reflected at the interfaces of a thin layer.
+
+- **In SolidCraft:** Glass `model.thin_film`, with `ior` and `thickness_nm`; this differs from an incoherent ideal Glass sheet.
+
### timeline
The ordered list of a design's features, which SolidCraft computes from first to last.
diff --git a/docs/render-cpu-general-glass.md b/docs/render-cpu-general-glass.md
index b3771786e3..c5cf6aa508 100644
--- a/docs/render-cpu-general-glass.md
+++ b/docs/render-cpu-general-glass.md
@@ -47,8 +47,15 @@ Separated bounds use the existing fast disjoint test. Overlapping selected close
bounds need a conservative nesting proof: each enclosing parent is convex and all
child vertices are strictly behind every outward parent plane. The immediate
parent is independent of body order; touching or crossing optical boundaries
-refuse. Nonconvex nested parents remain unsupported. Thin sheets retain their
-existing planar certificate and may not overlap another selected optical bound.
+refuse. Nonconvex nested parents remain unsupported. With Path, thin sheets accept
+connected exact planar tessellations, including concavity and holes, within the
+selected memory and cumulative work budget. All faces share one global winding;
+boundary edges have one face and interior edges have two opposite faces. Each
+vertex link forms one connected cycle or boundary path. Exact contact checks
+reject overlaps, T-junctions, duplicate faces and pinched or touching fans without
+repair. Signed zero has one coordinate identity. Without Path the original
+one/two-triangle sheet certificate remains unchanged. Sheets still may not
+overlap another selected optical bound.
Optical contact with analytic rectangle emitters or point/spot source positions
refuses explicitly. An ordinary opaque material wins an exact model-hit tie with
Glass, preserving an opaque contact surface instead of stepping past it.
@@ -89,15 +96,20 @@ area connections retain geometry-wins-endpoint ties; point/spot connections reta
their existing excluded-source endpoint. Closed refractive shadow connections are
**not implemented**: authored `shadow_transmission:true` on a closed target refuses
instead of silently using a straight-line approximation. Closed Glass still reaches
-HDR, area and mesh emission through actual sampled dielectric/GI paths. Point-light
-caustics and combining Glass with external participating volume remain unsupported.
+HDR, area and mesh emission through actual sampled dielectric/GI paths. Hard-source
+caustics require the separately authored photon prepass. Combining Glass with
+external participating volume remains unsupported.
The independent [bounded Atmosphere](render-cpu-volume.md) is an opaque-Path
-route; it does not erase those limits. No rough BTDF is added because the existing
-GPU Glass consumer is smooth delta transport.
+route; it does not erase those limits. Optional [Glass material models](render-glass-material-models.md)
+add rough transmission, three-band dispersion, lossless thin-film interference and
+finite-radius hard-source photon caustics. Assignments without a model keep the
+smooth route. These newer source changes have separate qualification from the
+historical CI7 counts above.
Certification is cooperative: exact edge merge sorting, connectivity, vertex links,
one face-pair contact check, determinant term or containment predicate run under
-the existing cumulative work and cancel token. For N selected closed triangles its
+the existing cumulative work and cancel token. For N selected optical triangles,
+including Path sheets as well as closed boundaries, its
prepaid peak is `sizeof(Task)+N*(sizeof(Face)+6*sizeof(Edge)+3*sizeof(usize)+3)`;
all vectors fallibly reserve exact capacity. The 12-limb volume state is in
`sizeof(Task)`. This change additionally bills one shared
@@ -123,29 +135,42 @@ work exhaustion, physical inside-eye and per-pupil nested Beer, first opaque and
analytic emission, exact boundary/near-clip refusal, initial-medium TIR, saved/runtime capture and the real pointer preset→Render→Save→
reopen workflow. The published source's tests executed in CI7; its exact counts
and failures are linked from [the qualification record](render-parity.md#qualification).
-The mathematical source reviews supplement those tests. A native Glass scene and
-image-quality acceptance remain pending; the opaque native fixture supplies neither.
+The mathematical source reviews supplement those tests. This earlier
+qualification used an opaque native fixture, so it did not establish native
+Glass controls or Glass image-quality acceptance. Later native Glass authoring
+and Save/reopen evidence is recorded separately with the
+[current Glass matrix](render-glass-complete.md) and
+[advanced material guide](render-glass-material-models.md). Control and persistence
+checks do not establish Glass/scattering image-quality acceptance.
## Subsurface continuation
The selected-medium continuation and its mathematical, producer, saved/runtime
-and pointer-UI regressions are part of the published source tested by CI7.
-Native Glass/scattering visual acceptance remains pending.
+and pointer-UI regressions are part of the earlier published source tested by CI7.
+Current native Glass control/persistence evidence has a separate scope; visual
+quality acceptance for Glass/scattering remains pending.
It consumes the existing saved `OpticalMaterial.subsurface` for a selected certified
closed CPU Path medium. The scalar collision rate is per millimetre; HG anisotropy
uses propagation directions, so positive values favor forward scattering. Beer
-absorption stays separate. There is no RGB scattering albedo, new rough BTDF,
-heterogeneous density or general external-volume consumer in this increment.
+absorption stays separate. There is no RGB scattering albedo, heterogeneous
+density or general external-volume consumer in this selected-medium model.
+Advanced interface models are independently authored optical controls.
Each actual inside-eye/pupil or post-surface segment samples free flight from the
physical segment start, before its closest model or analytic-emitter endpoint.
The primary near clip does not shorten that optical length. A collision consumes
one finite Path vertex, validates its actual f64 position against the current
-certified nested chain and launches one HG direction. It adds no ray tree, image
-plane, new sampler seed or cap. No-collision events retain their probability in
-endpoint MIS; contained direct-light connections use matching scattering survival
-and Beer absorption. No next-event connection through a refracting boundary is
-invented. Independently authored closed transmitted shadows stay refused.
+certified nested chain and launches one HG direction. The current continuation
+also estimates hard directional, point and spot illumination at that collision,
+including implicit studio directions. Supported contained connections include
+matching scattering survival and Beer absorption. The optional photon map admits
+rough-interface and HG volume receivers, with the bounded receiver reservoir,
+camera-path partition and finite-radius bias described in the
+[advanced material guide](render-glass-material-models.md). It adds no ray tree
+or image plane. No-collision events retain their probability in endpoint MIS.
+No arbitrary next-event connection through a refracting closed boundary is
+invented; those source paths require the optional photon estimate. Independently
+authored closed transmitted shadows stay refused.
Active scattering requires Path and disabled surface denoising, matching the
existing GPU random-walk compatibility domain. Thin sheets and Path=None retain
diff --git a/docs/render-cpu-path.md b/docs/render-cpu-path.md
index ccd6e6eb56..efab10cde8 100644
--- a/docs/render-cpu-path.md
+++ b/docs/render-cpu-path.md
@@ -24,8 +24,10 @@ with Path; authored values are retained. Selected-medium subsurface scattering,
bounded [Atmosphere](render-cpu-volume.md), Sun/Sky and independent-pilot adaptive
sampling are implemented and included in the published test suites. Active
Atmosphere cannot combine with Glass/SSS or surface Denoise. Active selected-medium
-scattering also requires disabled surface Denoise. Emissive-mesh next-event sampling,
-rough transmission and multithreading remain separate work. Every request still
+scattering also requires disabled surface Denoise. Optional [Glass material models](render-glass-material-models.md)
+add GGX rough transmission, three-band dispersion, one lossless coherent film and
+finite-radius hard-source photon caustics. Emissive-mesh next-event sampling and
+multithreading remain separate work. Every request still
has its own geometry, memory, work and compatibility admission.
The CPU Sampling control and CPU Glass transport entry point require explicit
progressive adoption for saved fixed choices. Disabling path lighting preserves
diff --git a/docs/render-cpu-progressive.md b/docs/render-cpu-progressive.md
index e757551daf..285533f3bc 100644
--- a/docs/render-cpu-progressive.md
+++ b/docs/render-cpu-progressive.md
@@ -15,8 +15,9 @@ optical transport. Explicit [opaque path lighting](render-cpu-path.md) adds boun
diffuse/specular continuation. Guided noise reduction is a separate saved option
applied to completed passes. Independent-pilot adaptive sampling, selected-medium
subsurface transport and general Glass are available under their explicit Path
-and compatibility contracts. Caustics and certified convergence remain unsupported;
-an adaptive sample allocation is not a convergence guarantee.
+and compatibility contracts. Optional [Glass models and photon caustics](render-glass-material-models.md)
+extend that explicit Path route. Certified convergence remains unsupported; an
+adaptive sample allocation or finite-radius photon estimate is not a convergence guarantee.
## Request and saved intent
diff --git a/docs/render-cpu-workspace.md b/docs/render-cpu-workspace.md
index 3554df9497..d902691665 100644
--- a/docs/render-cpu-workspace.md
+++ b/docs/render-cpu-workspace.md
@@ -102,7 +102,9 @@ The engine rejects a coated body or face selected for an incompatible reflection
path. Optional opaque path lighting supplies diffuse/specular indirect transport
through its separate explicit control; it cannot silently absorb incompatible
selected optical settings. [General Glass](render-cpu-general-glass.md) is an
-explicit Path capability; rough transmission and caustics remain unsupported.
+explicit Path capability. Optional [Glass material models](render-glass-material-models.md)
+add GGX rough transmission, three-band dispersion, one lossless coherent film and
+finite-radius hard-source photon caustics under their separate admission limits.
## Environment capture
diff --git a/docs/render-glass-boundaries.md b/docs/render-glass-boundaries.md
index 14ee874b28..86c7ddec4b 100644
--- a/docs/render-glass-boundaries.md
+++ b/docs/render-glass-boundaries.md
@@ -118,6 +118,14 @@ proof. Existing GPU certification checks welded closed/oriented homogeneous
connected topology and strict convex-parent nesting; it does not independently
prove a nonconvex leaf free from every self-intersection.
+The current source also uses the captured root bounds to prove vacuum before
+classifying a future silhouette: an origin outside that box is in air when the
+existing padded box entry misses or lies beyond the existing launch minimum.
+This reuses the query's first box-entry calculation. Near-boundary and in-bounds
+origins retain the complete query and its refusal policy. No origin, tolerance or
+sample stream is changed. The material-model publication record separately
+qualifies this newer proof; the historical suite below predates it.
+
The additional query runs only with explicit nested-media mode. It has a fixed
32-entry node stack and 32-entry depth array (256 bytes of shader private array
state), under the existing depth 30 host-built BVH. There is no new owned host
@@ -213,3 +221,35 @@ ray-origin-to-entry difference plus the remaining ray segment; it does not form
a rounded world endpoint. Geometry crossings are tested up to the true endpoint,
without applying the separate analytic-emitter self-intersection allowance.
The scatter history used by area-light MIS carries its associated local offset.
+
+## Certificate for the uploaded optical geometry
+
+Closed GPU Glass now also validates the positions actually consumed by the
+shader: source positions minus the camera target, rounded to f32. The original
+source certificate remains, and the uploaded-position certificate must pass as
+well. The legacy treatment of source-degenerate triangles remains: redundant
+pole faces in a latitude/longitude sphere mesh are skipped for both thin sheets
+and closed bodies. A selected optical body with no retained boundary refuses.
+Every retained face must remain valid after conversion; a face that collapses or
+reverses orientation in uploaded f32 positions refuses before rendering. The
+remaining closed boundary must also pass its topology and orientation proofs.
+
+Closed topology additionally requires one circular connected face fan at every
+welded coordinate vertex. A pair of shells joined only at a pinched vertex cannot
+pass solely because each edge has an opposite partner. The vertex-link proof
+reuses the existing prepaid face/edge scratch without adding an allocation.
+
+Optical bounds, nesting hierarchy and BVH geometry use the actual uploaded
+positions. A valid original mesh therefore cannot supply a certificate for a
+different rounded boundary. The existing coordinate, tolerance, bounded-work and
+cancellation policies remain. This strengthens admission; it does not prove
+general absence of self-intersection or universal exact watertightness.
+
+See the [detailed Glass matrix](render-glass-complete.md) for supported geometry,
+material limits and the headless evidence example. These source changes have
+their own validation scope; earlier captured renders do not qualify them.
+The same geometric boundary certificate surrounds the optional
+[rough, dispersive and coated interface models](render-glass-material-models.md).
+Their authored response changes transport at a valid boundary; it does not relax
+topology, nesting or origin admission. Photon-medium ambiguities fail separately
+and do not use the camera-path failure-fraction allowance.
diff --git a/docs/render-glass-complete.md b/docs/render-glass-complete.md
new file mode 100644
index 0000000000..5f143dbf2e
--- /dev/null
+++ b/docs/render-glass-complete.md
@@ -0,0 +1,184 @@
+# Glass transport and verification matrix
+
+CPU and GPU share saved Glass assignments and the mathematical dielectric
+contract. Each producer validates the captured geometry and transport options.
+The tables below state the supported domain and the remaining limits. They do
+not turn a saved control, a passing unit test or a rendered example into a claim
+that every glass material or light-transport effect is implemented.
+
+## Optical quantities
+
+All geometric distances are millimetres. IOR is a finite scalar in [1, 3]. The
+three absorption coefficients are finite linear-RGB values in [0, 100] per mm.
+Absorption is independent of the opaque base colour and scalar preview opacity.
+
+For geometric path length d, channel transmission is `exp(-sigma * d)`.
+A desired channel transmission T at positive distance d corresponds to
+`sigma = -ln(T) / d`. T is linear transmission, not an encoded sRGB colour.
+Zero absorption preserves radiance between interfaces. Positive absorption
+depends on actual thickness and angle; tint is not a surface colour overlay.
+
+Both producers use Snell refraction and exact unpolarized dielectric Fresnel.
+The s and p power reflectances are computed separately and averaged. Radiance
+transmission includes the squared incident/transmitted IOR ratio. Total internal
+reflection produces a reflected continuation with no transmitted branch.
+An index-matched interface reflects zero, including the limiting grazing case.
+
+An uncoated smooth ideal sheet combines both parallel interfaces and all incoherent internal
+reflections. It absorbs over `thickness / refracted_cosine` and leaves the
+transmitted direction unchanged. Zero thickness still retains the two-interface
+response. The sheet has no interior region or lateral displacement. An optional
+advanced material adds rough interfaces, dispersion and a coherent single-layer
+coating; see [Glass material models](render-glass-material-models.md). Geometric
+sheet absorption, coating interference and a closed solid are distinct models.
+
+## Geometry and transport
+
+| Case | CPU ray tracing | GPU path tracing |
+| --- | --- | --- |
+| Clear closed glass | Explicit Indirect lighting (Path), progressive camera sampling, traced shadows and `primary_samples: 1`; smooth or explicitly authored rough interfaces. | Smooth or explicitly authored rough interfaces; progressive fixed or adaptive sampling. |
+| Tinted or absorbing glass | RGB Beer attenuation over physical segments, including the segment from an inside eye or sampled pupil. | RGB Beer attenuation between geometric endpoints; numerical launch adjustment does not shorten absorption. |
+| Ideal parallel sheet | Path accepts a connected exact planar tessellation, including concavity and holes, within its work/memory budget; explicit thickness and exact slab Fresnel/Beer response. The legacy route retains its one/two-triangle domain. | Captured sheet surface, explicit thickness and exact slab Fresnel/Beer response. |
+| General closed shape | Exact captured-f64 closed-manifold, vertex-link, contact, self-intersection and outward-volume certificate. No seam welding or geometry repair. | Source and actual camera-relative uploaded-f32 topology, circular vertex-link and outward-orientation certificates with bounded seam matching. General absence of self-intersection is not proved. |
+| Hollow vessel | One connected outward boundary may include inner walls and an open air cavity. Each real interface is traversed. | Same physical boundary model, subject to the GPU certificate and precision contract. |
+| Disconnected shells in one selected body | Refused. Author separate optical bodies with unambiguous material boundaries. | Refused. A body must have one connected shell. |
+| Strictly nested solids or an air bubble | Path proves a strict containment hierarchy with convex enclosing parents. Inner IOR 1 can represent an air region. | Explicit `nested_media: true` and its strict convex-parent containment certificate. |
+| Touching, crossing or overlapping selected media | Refused when the optical certificate cannot establish a unique strict hierarchy. | Refused by the admitted hierarchy policy. No overlapping-medium repair or material-priority rule. |
+| Camera or pupil inside a solid | Physical origin classification initializes the ordered medium stack. Boundary and near-clip crossings use the documented refusal policy. | Explicit nested mode performs the shader origin classification; default outside-origin policy remains. |
+| TIR and grazing interfaces | Geometric winding and correct incident/transmitted medium select the physical branch. | Same mathematical branch policy within f32 intersection and origin limits. |
+| Opaque objects behind or beside glass | Supported. Ordinary opaque surfaces retain their supported PBR, maps, aging and clear coat. | Supported within each opaque feature's GPU admission. |
+| Opaque object embedded inside glass | Actual sampled paths remain physical; opaque contact ties preserve opaque material. | Actual sampled paths remain subject to medium classification; enabled solid shadow approximation has separate limits. |
+| Glass surface plus opaque maps or clear coat | A single target cannot combine Glass with opaque maps or clear coat. Unsupported authored combinations refuse. | Same saved-target policy. |
+| Selected-medium scattering | Homogeneous elastic free flight and HG phase inside a certified closed Path medium; surface Denoise must be off. | Homogeneous random walk inside selected closed media; Denoise off, one Fresnel stratum and no active external volume. |
+
+The saved editor resolves definition, feature, component and occurrence targets.
+The raw runtime adapter instead binds an exact captured ordinal and body name.
+These are separate binding lanes; mixing them is refused. Runtime overrides do
+not change design appearances, engineering materials, mass or geometry.
+
+The common runtime command contract admits at most eight overrides. Internal GPU
+scene capacities are not a promise that a saved or runtime command accepts more.
+CPU and GPU retain their individual memory, geometry, work and path-depth bounds.
+Certification failure preserves authored input and produces no partial proof.
+
+Path sheet certification charges each captured face, edge operation, vertex link
+and exact contact check through the existing cooperative budget. Boundary edges
+have one incident face; interior edges have two oppositely directed incident
+faces. Vertex fans form one connected cycle or one boundary path. Folded,
+disconnected, duplicated, overlapping, nonmanifold and pinched sheets refuse.
+T-junctions are not repaired. Equal authored coordinates can join without relying
+on shared vertex indices; signed zero has one exact geometric identity.
+
+The GPU additionally certifies the positions actually uploaded after subtracting
+the camera target and rounding to f32. Its legacy source-degenerate triangle
+skip remains compatible with redundant sphere pole faces in thin and closed
+bodies. A selected optical body with no retained boundary refuses. Each retained
+face must remain valid after conversion: f32 collapse or orientation reversal
+refuses before rendering. Closed boundaries also need the complete topology and
+orientation proofs. Bounds, hierarchy and optical BVH geometry use the consumed
+positions. This prevents a valid source mesh from advertising a proof for
+different consumed geometry. It does not remove finite-precision limits or add
+a general self-intersection proof.
+
+## Lighting, sampling and output
+
+| Effect or combination | CPU | GPU |
+| --- | --- | --- |
+| Environment, HDR or analytic rectangle reached by a glass path | Physical sampled specular continuations reach the endpoint. | Physical sampled specular continuations reach the endpoint. |
+| Thin-sheet transmitted direct shadows | Explicit Path shadow transmission uses the smooth RGB slab, including dispersion/film, and matching light/BSDF MIS probabilities. Rough sheets refuse straight shadows. | Enabled by raw smooth-sheet default; slab transmission and matching MIS history, including optional spectral/film response. Rough sheets refuse straight shadows. |
+| Closed-solid transmitted direct shadows | Explicit `shadow_transmission: true` refuses. Physical sampled glass paths still reach extended emitters. | Opt-in straight-through NEE approximation; 64-interface limit. It replaces the corresponding transmitted direct estimate. |
+| Hard directional, point or spot illumination at rough Glass or selected HG collisions | Explicit direct connections use dielectric projected BSDF or phase; supported visibility connections and finite depth apply. | Same estimator, including implicit studio directions. Ideal pure-delta source endpoints retain their existing visibility convention. |
+| Focused caustics from hard directional, point or spot sources | Opt-in bounded photon tracing with rough/interface, HG and opaque receivers, a uniform bounded receiver reservoir and finite-radius density estimation. | The same receiver domain and reservoir under the seven-storage-buffer variant. Solid shadow approximation remains separate. |
+| External participating atmosphere plus glass | Refused. The bounded atmosphere consumer is an opaque-Path route. | Refused by the active homogeneous-volume route. |
+| Physical depth of field | Explicit lens under the CPU optical/pupil certificate. | Explicit lens under GPU origin and nested-medium admission. |
+| Adaptive sampling | Independent pilots and retained production samples under the selected CPU profile. | Independent pilots and bounded per-pixel production allocation. |
+| Denoising | Surface guide filter bypasses glass and sharp first hits; raw EXR remains unfiltered. Active scattering combinations refuse. | Same surface-filter limitation; not a glass-transport or depth-of-field reconstruction model. |
+| PNG and raw EXR | Completed frame owns its display PNG and optional raw scene-linear master. | Completed frame owns its display PNG and optional raw scene-linear master. |
+| Transparent background | Coverage alpha is not a general transmissive compositing matte. | Same distinction. |
+
+A finite maximum depth truncates paths; a completed render does not prove
+convergence. The CPU and GPU use different sampling streams, geometry precision
+and light estimators. Equal settings do not imply equal noise or identical pixels.
+
+## Material models and remaining limits
+
+| Requested appearance or phenomenon | Current status |
+| --- | --- |
+| Frosted, etched or sandblasted rough glass | Explicit isotropic single-scattering GGX reflection/transmission is supported. General anisotropic or measured microsurface models remain absent. |
+| Chromatic dispersion, rainbows and Abbe numbers | Explicit bounded Abbe/Cauchy IOR is supported at three representative RGB wavelengths; not dense spectral rendering or measured Sellmeier glass data. |
+| Thin-film interference, iridescence or coherent films | One lossless coherent dielectric coating is supported. Multilayer stacks, absorbing coatings and spectral anti-aliasing remain absent. |
+| Polarized transport, birefringence or anisotropic crystals | Fresnel uses averaged s/p power; no retained polarization state or tensor IOR. |
+| Heterogeneous, textured or spatially varying interior media | No heterogeneous selected-medium density or RGB scattering albedo. |
+| Fractional mixtures of opaque and transmitting closures | No fractional transmission-weight field. Scalar opacity remains a separate raster-preview property. |
+| General nonconvex nested parents | No general nesting proof for nonconvex enclosing parents. |
+| Arbitrarily intersecting media, touching liquid menisci or overlapping priorities | No implicit boundary repair, epsilon gap creation or medium-priority solver. |
+| Full refracted direct-light silhouettes and general caustics | Hard-source photon caustics use a finite-radius biased estimate. No general unbiased specular-chain solver or convergence guarantee. The GPU optional straight shadow connection is separately approximate. |
+
+The [material-model guide](render-glass-material-models.md) details the authored
+models, representative wavelength limits and finite-radius caustic bias.
+Remaining limits require new transport, material-authoring or certification work;
+removing an admission guard does not implement the missing effect.
+
+## Reproducible headless images
+
+The original [`glass_comparison` example](../crates/gpu/examples/glass_comparison.rs)
+uses the public CPU and GPU hosts. It builds fourteen public-safe scenes from explicit
+triangle positions without the CAD kernel or external assets:
+
+| Case | Geometry and visible purpose |
+| --- | --- |
+| `clear` | Nonabsorbing rectangular solid in front of an opaque checker board. |
+| `tinted` | The same solid with RGB absorption `[0.065, 0.012, 0.003]` per mm. |
+| `hollow` | One connected 3 mm thick square vessel, inner walls and solid bottom. |
+| `nested` | Absorbing outer box and strictly enclosed index-1 air box. |
+| `sheet` | One ideal 3 mm sheet with opaque checker board and floor. |
+| `rough` | Closed glass with explicit GGX roughness 0.35. |
+| `dispersion` | An original triangular prism with an illustrative Abbe number of 15. |
+| `film` | A 400 nm, IOR 1.35 lossless dielectric film on clear glass. |
+| `rough_sheet` | A 3 mm virtual sheet with independent rough interfaces. |
+| `caustics` | A faceted sphere over a receiver, one hard directional source, 65,536 photons and 0.75 mm gather radius. |
+| `rough_lights` | A rough closed solid illuminated only by a blue directional, red point and green spot light; no environment or area emission. |
+| `rough_sheet_lights` | The same hard-only source family on a 3 mm rough virtual sheet. |
+| `rough_caustics` | A roughness-0.2 faceted sphere, hard directional light and the surface photon map; no environment or area emission. |
+| `scattering_caustics` | A closed HG medium with scattering 0.06/mm and anisotropy 0.35; hard directional light, 65,536 photons and a 2 mm volume/surface gather radius. |
+
+All scenes use IOR 1.5 for the glass, 16 path vertices, seed 81, no denoising and
+no display effects. The sphere caustic scenes use a higher camera elevation and
+a receiver 5 mm below the sphere. The common camera is perspective with a 0.65
+radian vertical field of view. The original ten cases use constant environment
+radiance `[0.7, 0.8, 1]` and one rectangle with radiance `[4, 4, 4]`. The four
+additional hard-source cases explicitly disable both. The CPU uses four samples
+per enabled area connection; GPU uses its native estimator. The source code and
+each saved receipt contain every hard-light position, direction, distance/cone
+parameter and intensity. Neither producer enables the GPU solid-shadow
+approximation. Adding a reproducible scene is not a claim that it has passed a
+physical backend or image-quality review; publication records name actual runs.
+
+From the repository root, choose an output directory that does not yet exist:
+
+```sh
+cargo run --locked --profile ci -p solidcraft-gpu \
+ --features solidcraft-render/raytrace-cpu --example glass_comparison -- \
+ /tmp/solidcraft-glass-evidence both 32 all 256
+```
+
+Arguments after the directory select `cpu|gpu|both`, 1–64 samples per pixel,
+one case from the table or `all`, and width 64–1024. Height is three quarters
+of width, rounded down. Missing GPU support produces an error; it does not count
+as a successful GPU execution or silently substitute a CPU image.
+
+Each completed case writes its actual PNG, raw EXR and a JSON receipt. Receipts
+record the exact request, options, captured vertices/triangles, per-face geometric
+normals, face IDs, material/optical values, executor metadata,
+frame identity and raw-master digest. Failure or timeout does not write a PASS
+receipt. The example refuses an existing output directory to preserve evidence.
+Generated media belong outside the repository and are not source assets.
+
+This example verifies headless job completion and same-frame image ownership.
+It does not exercise desktop controls, saved stable bindings, Save/reopen,
+cancellation, every adapter, default quality or image-quality acceptance.
+Mathematical oracles and negative geometry tests provide independent evidence
+for their asserted quantities; a pleasing image cannot replace those checks.
+See [renderer parity](render-parity.md), [CPU general Glass](render-cpu-general-glass.md),
+[GPU boundaries](render-glass-boundaries.md) and [shadow connections](render-glass-shadows.md)
+for the existing algorithms and their separately qualified scopes.
diff --git a/docs/render-glass-material-models.md b/docs/render-glass-material-models.md
new file mode 100644
index 0000000000..a960a08aaf
--- /dev/null
+++ b/docs/render-glass-material-models.md
@@ -0,0 +1,376 @@
+# Rough Glass, dispersion, thin films and caustics
+
+Glass assignments can optionally carry a bounded material model. CPU Indirect
+lighting and GPU path tracing consume that model from the same saved optical
+assignment. Existing assignments without `model` keep their smooth-dielectric
+interpretation and existing sampling route. The additional controls describe
+optical rendering; they do not change engineering materials or mass.
+
+```json
+{
+ "model": {
+ "roughness": 0.2,
+ "dispersion": { "abbe_number": 60 },
+ "thin_film": { "ior": 1.38, "thickness_nm": 285 }
+ }
+}
+```
+
+Each field controls a separate effect. Omit `dispersion` or `thin_film` to disable
+that effect. Roughness zero selects a smooth interface. A zero-thickness film
+has the exact bare-interface response. The editor preserves authored values and
+reports incompatible combinations instead of silently clearing them.
+
+## Rough reflection and transmission
+
+`roughness` is finite in [0, 1]. It controls an isotropic GGX microfacet boundary,
+with slope width `alpha = roughness²`. This is an optical Glass parameter;
+opaque appearance roughness is not reinterpreted as transmission roughness.
+Numerically unrepresentable positive widths or GGX peaks refuse; they are not
+silently raised to a larger roughness. GPU f32 precision can refuse a width that CPU f64 admits.
+
+For positive GPU roughness, the uploaded f32 slope width must also have a
+**normal**, rather than merely nonzero, squared width: `alpha² >= 2^-126`
+(`f32::MIN_POSITIVE`), with a finite GGX peak. WGSL permits specified arithmetic
+inputs/results to flush subnormal values to zero; a finite theoretical peak can
+therefore still produce a zero microfacet denominator. See the
+[WGSL floating-point rules](https://www.w3.org/TR/2026/CRD-WGSL-20260825/#floating-point-evaluation).
+For example, roughness `1e-9` meets this admission, while `3e-10` does not.
+The CPU f64 domain is unchanged, and roughness zero retains the smooth limit.
+Projected-response products or ratios outside safe GPU arithmetic also produce
+an explicit optical-arithmetic failure rather than a clamped BSDF or invalid image.
+
+The sampler draws visible microfacet normals for the incident direction. Exact
+Fresnel selects reflection or transmission at the sampled facet. The transmitted
+direction follows Snell refraction. Total internal reflection selects reflection.
+Height-correlated Smith masking supplies the single-scattering geometric weight.
+The continuous evaluator uses the same reflection/refraction mixture and
+refraction Jacobian as the sampler. A sampled direction on the wrong geometric
+side contributes zero; retrying until it passes would change the estimator.
+
+For radiance transport, transmission carries `(incident_ior / transmitted_ior)²`.
+Photon flux transport uses the corresponding importance convention and does not
+multiply flux by that radiance ratio. Jobs with an active advanced model or
+caustics use the geometric facet normal for optical sampling and evaluation.
+This fixed facet normal gives reciprocal transport. Smooth Glass jobs without
+either option use their original shading-normal policy, including when the
+selected medium scatters. Opaque receivers use their supported authored shading
+normals. Matched indices without an effective film retain a straight
+unit-transmission delta event, including with authored roughness.
+
+The model is single scattering on the microsurface. It does not add an empirical
+energy-compensation term or claim a multiple-scattering GGX microsurface solution.
+Macro-scale paths can still bounce through several actual Glass boundaries.
+An ideal rough sheet walks its entry/exit interfaces and internal returns within
+the finite authored path depth. That walk is distinct from coherent thin-film
+interference and from a closed geometric solid.
+
+The VNDF construction follows the published mathematical description in
+[Heitz (2018)](https://jcgt.org/published/0007/04/01/paper.pdf). The transmission
+half-vector and Jacobian follow
+[Walter et al. (2007)](https://www.graphics.cornell.edu/~bjw/microfacetbsdf.pdf).
+The implementations are original Rust and WGSL derived from the equations.
+
+## Hard-source direct lighting
+
+Rough closed interfaces and each rough virtual-sheet interface explicitly
+connect to hard directional, point and spot sources. The three implicit studio
+directions use the same estimator when no explicit lighting setup is authored.
+The contribution is the continuous dielectric BSDF times the outgoing projected
+cosine, source radiance and the supported shadow connection. Point/spot sources
+retain their distance and cone attenuation. These deterministic connections have
+unit MIS weight: a continuous BSDF sample cannot hit a zero-solid-angle source.
+The GPU's selected-vertex factor K is a separate importance weight, described
+below. Finite rectangles, finite suns, emissive geometry and environments retain
+their separate sampled endpoint estimators.
+
+GPU straight closed-solid shadows remain a separate, optional approximation.
+For smooth jobs using the legacy approximation, a completed closed crossing
+uses its Fresnel and Beer scale. A connection that stays in one medium
+integrates that medium's Beer attenuation and cancels the equal-endpoint IOR
+factors. Advanced optical transport applies the endpoint IOR ratio at crossings.
+
+When an opaque camera prefix is already covered by that transmitted-light
+estimate and the current rough closed material enables it, hard-source NEE at
+the rough interface retains only reflection. Adding its transmitted response
+would count the replaced family again. Camera/specular-only prefixes retain
+the full rough response. A reflection turn or a material with disabled straight
+shadows breaks the replaced transmission chain, so later physical connections
+remain available. Reflection-only connections retain their actual incident
+medium and its absorption; they are not treated as virtual sheets or vacuum.
+This partition does not make the straight approximation a refracted-shadow
+solver. Closed-shadow approximation still refuses with caustics, and rough
+virtual sheets still require disabled straight transmitted shadows.
+
+At a virtual sheet's world-facing entry, a direct reflected connection can leave
+the sheet. At an internal return, a transmitted connection can leave it. The
+finite interface walk includes the corresponding Fresnel/Beer factors and depth
+limit. A later zero-contribution continuation does not erase an earlier direct
+contribution. A legal straight smooth-sheet shadow connection can attenuate a
+light connection; this does not add an arbitrary refracted shadow solver through
+another closed or rough boundary.
+
+Selected HG collisions also connect to those hard sources with the normalized
+phase function. The phase angle compares physical propagation directions;
+positive anisotropy favors forward scattering. Ideal smooth delta interfaces
+do not acquire a continuous highlight from these connections. Ideal hard-source
+endpoints remain nonvisible to pure specular camera paths under the existing
+emitter convention.
+
+The GPU uniformly retains one eligible optical/HG vertex for hard-source NEE,
+then stores that request for a separate optical-resolve dispatch after the
+camera walk. If K vertices were eligible and J is the uniformly selected vertex, the
+result is `K * prefix_J * direct_J`. Conditioned on the camera path, its expected
+value is `sum_i prefix_i * direct_i`, by the same uniform-reservoir identity as
+the photon receiver selection below. This retains the complete expected direct
+sum while storing one request. CPU continuation estimates its eligible vertices
+through its cooperative connector.
+
+The retained GPU payload uses six `vec4<u32>` lanes: 96 bytes plus separate count
+and selection RNG state. It preserves the physical point's high/low parts,
+incident direction, IORs, source triangle/event kind and throughput prefix; HG
+requests also retain their current medium. Certified parent metadata reconstructs
+closed-interface media. The existing sixteen-event camera limit, including every
+consumed virtual-sheet interface, bounds K by 16; an exceeded count fails
+explicitly.
+
+The camera dispatch writes a 128-byte packet per active path in its bounded
+tile: 96 bytes of selected request, 16 bytes of count/wavelength and 16 bytes of
+already accumulated camera-path RGBA. Optional tile scratch is
+`128 * min(image_pixels, 16384)` bytes, at most 2 MiB, prepaid and appended to the
+existing accumulation buffer. It adds no uniform or storage binding and no
+full-image auxiliary plane. Fixed film uses its original one-plane offsets;
+adaptive film keeps its three pilot/production/budget-plane offsets. Packet
+scratch follows those planes and uses the path's tile-local index. Triangle and
+mode identifiers are numerically encoded in f32 storage lanes and recovered as
+integers; the eight-million-triangle host limit keeps those IDs exactly
+representable, and the HG event ignores its triangle sentinel.
+
+A separate resolve dispatch computes the selected hard-light visibility, adds
+its K-weighted contribution to the stored camera value, and performs the shared
+film update. Camera and resolve use matching active-pixel/adaptive-budget guards;
+only resolve updates the optical job's film. Fixed sample scaling, Fresnel
+strata, pilot variance/budget selection and final adaptive normalization therefore
+occur once per retained camera sample. Both pipelines are warmed with the actual
+admitted bindings before production. The ordinary inactive route retains its
+single-dispatch film update and original storage domain.
+
+Selection has its own RNG domain and does not consume or modify transport RNG
+state or camera sampler dimensions. Null, depth-limited and ordinary terminated
+continuations preserve the retained estimator; invalid-medium paths keep their
+existing diagnostics. Selecting one request adds variance when caustics are off
+and several continuous optical/HG vertices contribute. With caustics enabled,
+the first-continuous-event partition usually leaves K = 1; preceding mixed
+coated/index-matched delta choices can still leave several eligible requests.
+The photon gather remains a separate estimator with its own receiver reservoir.
+
+The separate optical program keeps its visibility/BVH walk out of the camera
+continuation program. Native driver qualification remains necessary: passing a small
+traversal or isolated lighting probe does not establish correctness of the full
+expanded path integrator.
+
+## Dispersion and the three representative wavelengths
+
+`dispersion.abbe_number` is finite in [5, 200]. The authored Glass IOR is `nd`,
+the index at the helium d line, 587.5618 nm. A two-term Cauchy approximation fits
+that index and `vd = (nd - 1) / (nF - nC)`, using F = 486.1327 nm and
+C = 656.2725 nm. The fitted index must stay in [1, 3] over 380–780 nm; invalid
+material pairs refuse rather than clamp the index.
+
+With `B = ((nd - 1) / vd) / (1/F² - 1/C²)`, the model evaluates
+`n(lambda) = nd + B * (1/lambda² - 1/d²)`. Wavelengths in that expression are
+nanometres. The resulting shorter-wavelength rays refract more strongly for
+normal positive dispersion. Dispersion can split focused or refracted RGB bands;
+it is not an image-space chromatic-aberration effect.
+
+The renderer represents R, G and B by **610, 550 and 460 nm**, respectively.
+When a path needs wavelength-dependent directions, one band is selected and
+weighted by its inverse selection probability. The band remains fixed through
+that path's directional optical interfaces and medium stack. Smooth ideal sheets
+can instead evaluate all three bands in their RGB slab closure: straight
+transmission does not require a band-dependent direction. The CPU camera,
+transmitted-shadow and photon consumers share that slab closure and its scalar
+mean-proposal branch probability. Photon transport uses the same representative
+bands. Absorption remains the authored RGB coefficients.
+
+This is a three-band approximation. It does not integrate a continuous spectrum,
+measured source spectra, CIE colour-matching functions or a named glass's measured
+Sellmeier coefficients. It can show band separation, but it does not promise
+spectrally accurate rainbow colour, narrow-band light response or colourimetry.
+Abbe number and `nd` alone do not identify a unique real glass.
+The definitions and wavelengths come from the manufacturer's
+[SCHOTT TIE-29](https://media.schott.com/api/public/content/aaa572afd854434fb7b3faa4bc46103f?v=c0f4fa52).
+
+## Coherent single-layer thin film
+
+`thin_film.ior` is finite in [1, 3] and `thickness_nm` in [0, 100000]. This is a
+single lossless dielectric coating on each optical interface. Its thickness is
+nanometres, independent of an ideal sheet's millimetre absorption thickness or a
+closed body's geometric thickness.
+
+Complex Fresnel amplitudes combine the two film interfaces and their repeated
+internal reflections through the coherent Airy sum. The s and p power responses
+are computed separately before averaging. The film can be propagating or
+evanescent; a thin evanescent film can tunnel energy into a transmitting substrate.
+The final transmitted direction still follows the actual outside/substrate
+indices. The film does not create a laterally displaced geometric boundary.
+
+A small-phase transfer-matrix form remains finite at the exact film critical
+angle, where directly dividing the two Airy amplitude sums can produce 0/0.
+Zero film thickness bypasses the coating and reproduces bare Fresnel exactly.
+An index matched to either adjacent medium preserves bare-interface power.
+Substrate total internal reflection retains unit reflectance.
+
+Only the local coating retains coherent phase. Separate Glass boundaries and
+macro-scale paths combine radiance, not wave amplitudes. There is no multilayer
+stack, absorbing complex film index, diffraction grating or propagated
+polarization state. Three representative wavelengths can alias rapid film
+oscillations and produce colours different from dense spectral integration,
+especially for thicker films. The analytical spectral anti-aliasing technique of
+[Belcour and Barla (2017)](https://hal.science/hal-01518344/document) is not claimed
+here; that paper also explains the underlying Airy model and spectral aliasing.
+
+## Caustics from directional, point and spot lights
+
+The saved CPU/GPU job can independently enable the following bounded prepass:
+
+```json
+{
+ "caustics": {
+ "photons": 16384,
+ "radius_mm": 1,
+ "max_depth": 16,
+ "seed": 81
+ }
+}
+```
+
+The CPU request carries these settings in its ray-tracing options; GPU jobs carry
+them in the progressive job options. The Render workspace saves them with the
+setup. Enabling caustics does not change existing Glass materials or renderer
+quality defaults.
+
+`photons` is 1–65536, `radius_mm` is finite in [0.000001, 1000000], and light-path
+depth is 1–16 events. The photon seed is independent of the camera sampler.
+Sources are hard directional lights, point lights and spot lights, including the
+existing three implicit studio directions when that lighting mode is active.
+Directional emission covers the captured scene bounds; point and spot emission
+uses the corresponding bounded source conventions.
+
+The prepass follows actual reflected and refracted optical paths, including rough
+interfaces, wavelength-dependent IOR, coatings and supported selected-medium HG
+scattering. Eligible receivers include rough dielectric interfaces, virtual-sheet
+interface sides, selected HG collisions and the first opaque surface. Light paths
+continue after rough or HG receiver visits and stop at the first opaque surface.
+A first rough/HG event with no prior optical event is direct illumination, already
+covered by direct-light sampling, and is not also stored as a caustic. Smooth
+straight sheet transmission covered by the existing direct connection likewise
+does not create another copy of that contribution.
+
+One launched photon stores **at most one** of its eligible receiver visits. If a
+path has K eligible visits, uniform reservoir selection gives every visit
+probability 1/K, and the selected record stores K times that visit's flux.
+Conditioned on the traced path, the expected gathered contribution is therefore
+`sum_i (1/K) * K * flux_i * response_i = sum_i flux_i * response_i`.
+K is bounded by the authored maximum light-path depth, at most 16. The final
+estimate divides by launched photons, including paths with no deposit, rather
+than the number of retained records. This bounds storage without silently
+truncating later receivers; the reservoir adds variance.
+
+Surface receivers use a uniform disk kernel `1 / (pi * radius²)` and compatible
+normal/plane checks. The receiver BSDF multiplies deposited flux per geometric
+area. For an opaque shading normal ns and geometric normal ng, the measure
+conversion is `abs(incoming_light.ns) / abs(incoming_light.ng)`: deposited flux
+already contains geometric projected incidence, so there is no second cosine.
+Photon continuation uses the adjoint normal factor
+`abs(wo.ns) * abs(wi.ng) / (abs(wo.ng) * abs(wi.ns))` after removing the radiance
+IOR ratio; wo points back along the incoming photon and wi follows its outgoing
+travel. These are fixed-normal transport measures derived from
+[Veach (1997), sections 5.3.3–5.3.4](https://graphics.stanford.edu/papers/veach_thesis/thesis.pdf).
+Exact tangent measures contribute zero; invalid or nonrepresentable measures
+refuse instead of introducing a normal epsilon.
+
+At an analog camera HG collision, the volume gather uses the ball kernel
+`3 / (4 * pi * radius³ * scattering_per_mm)` times phase and photon flux.
+The light collision density contains one scattering coefficient, while analog
+camera free-flight sampling already accounts for its own collision probability;
+dividing by that coefficient recovers fluence in this estimator. A path-integrated
+ray-marching estimator has a different measure. The kernel's units are inverse
+square millimetres, consistent with a flux-to-radiance estimate.
+
+With caustics enabled, rough/HG direct connections and map gathering operate up
+to the eye path's first actually sampled continuous event. Subsequent continuous
+continuations do not also add the same photon-represented source paths. A coated
+index-matched delta transmission is not a continuous event. Opaque direct lighting
+and gathering remain enabled: light prepasses stop at their first opaque visit.
+Finite-area lights and the environment remain under camera-path estimators and
+are never emitted into this hard-source map.
+
+**This is a finite-radius density estimate.** It is biased at finite radius and
+has finite-photon variance. Radius controls blur and geometric leakage; photon
+count controls sampling density. A smaller radius can produce a sparse or noisy
+estimate. Close surfaces and curvature still matter despite normal/plane checks.
+A completed job does not prove convergence or exact caustic silhouettes.
+There is no general bidirectional connection, manifold next-event solver or
+unbiased specular-chain estimator implied by the Caustics control.
+
+CPU preparation follows its cooperative work and cancellation budget. GPU uses
+measured bounded clear/emission quanta and a prepaid photon hash table. The hash
+has a power-of-two head count of at least twice the photon count and at most one 64-byte
+receiver record per launched photon. GPU grid span must not exceed 2²⁰ radius cells on any axis.
+The ordinary six-storage-buffer GPU route remains available on older devices;
+only authored caustics require the separate seven-storage-buffer variant.
+
+GPU punctual-source origins too close to a closed optical boundary for reliable
+rounded medium classification refuse explicitly. A detected photon medium
+ambiguity also fails the job; it is not folded into the camera-path tolerance or
+silently discarded while still reporting a successful image.
+
+Active external atmosphere remains incompatible with this photon prepass.
+Enabled straight closed-solid shadow approximation also refuses with caustics;
+the approximation and photon estimate must not count the same hard direct light.
+Selected-medium scattering keeps its existing surface-denoiser and Fresnel-strata
+restrictions. General overlapping optical media and nonconvex nested-parent
+certification remain separate geometry limitations.
+
+Rough ideal sheets require disabled straight transmitted shadows. Smooth sheets
+with dispersion or coating interference retain the RGB slab shadow connection
+and matching light/BSDF mixture probability. Closed-solid CPU shadow connections
+remain unsupported; the physical camera and optional photon paths still refract
+through those solids.
+
+## Verification and practical limits
+
+The shared mathematical tests cover exact bare and zero-film limits, the Abbe
+definition, Brewster and TIR cases, quarter-wave anti-reflection, film thickness
+periodicity, evanescent tunnelling, film critical-angle continuity, reciprocal
+power, VNDF normalization and `f * abs(cos) / pdf` sample weights. A rough
+single-scattering furnace rejects energy gain; it does not assert unit energy
+after unmodelled microsurface multiple scattering. Independent tests also check
+the normal-incidence hard-directional GGX response `F / (4 * pi * roughness^4)`,
+projected evaluator/sample agreement, adjoint normal and surface-density measures,
+volume units/scattering cancellation, and exact integer reservoir history counts
+for every eligible path length from 1 through 16. These mathematical identities
+require separate production-path tests to establish consumer integration.
+
+Producer tests separately qualify CPU and GPU consumption, photon storage and
+transport, saved/runtime capture and image output. Qualification must name the
+tested source and adapter. Mathematical tests do not establish an application UI
+capture, all-adapter acceptance or default-quality approval.
+
+The publication record must supply the following results for this implementation.
+Earlier smooth-Glass or opaque-render receipts do not fill these entries.
+
+| Scope | Required qualification record |
+| --- | --- |
+| Shared mathematical functions | Exact tested source identity and numerical test result; distinguish a standalone source harness from the complete crate suite. |
+| CPU producer | Complete renderer test result plus advanced material and photon images from the recorded source. |
+| GPU shader structure | Both legacy six-buffer and caustic seven-buffer WGSL validation results; structure alone is not device execution. |
+| Physical GPU producer | Adapter/backend, exact source, advanced material/caustic tests and completed images. |
+| Saved/runtime/UI integration | Exact tests and any actual author/save/reopen evidence; API-only images do not establish pointer UI acceptance. |
+| Repository gate | Actual `cargo xtask ci` result and any inherited failures, without promoting scoped passes into a green full-suite claim. |
+
+See the [complete Glass matrix](render-glass-complete.md),
+[CPU general Glass](render-cpu-general-glass.md),
+[GPU boundary certificate](render-glass-boundaries.md) and
+[renderer parity](render-parity.md) for the surrounding contracts.
diff --git a/docs/render-parity.md b/docs/render-parity.md
index f4c9e77dc0..a95a12091c 100644
--- a/docs/render-parity.md
+++ b/docs/render-parity.md
@@ -28,7 +28,8 @@ remains schematic; it is not physical Glass, GI or an alternate path tracer.
| Selected reflection/anisotropy overrides | Existing direct/legacy contracts remain. Selected overrides refuse with Path; no silent clearing or reinterpretation. | No equivalent CPU planar selected-anisotropy adapter. HG phase anisotropy is a different parameter. |
| Guided denoising | Complete displayed passes are filtered; Glass and sharp specular first hits bypass. Raw EXR remains unfiltered. Active medium restrictions above remain. | Same distinction: surface guide filter, not a Glass/DOF ML denoiser; raw accumulation stays intact. |
| Physical lens and output | Explicit lens; straight-alpha primary coverage PNG and compatible finishing; completed raw EXR. Glass is not a general transmissive compositing matte. | Explicit lens, compatible PNG/finishing and completed raw EXR under its own admission. |
-| Rough Glass and caustics | No rough BTDF or refracted-caustic solver. | Smooth delta Glass only; no rough BTDF or general refracted-caustic solver. |
+| Rough Glass, dispersion and coating interference | Optional isotropic GGX reflection/transmission, bounded Abbe/Cauchy dispersion and one lossless coherent coating; explicit Path. Three representative RGB bands. | Same authored models with f32 arithmetic and its precision refusals; three representative RGB bands. |
+| Hard-source caustics | Opt-in bounded photon paths and finite-radius density estimate. | Opt-in bounded photon paths and finite-radius density estimate; lazy seven-storage-buffer pipeline. |
Stable Glass, opaque coats and built-in maps save with the shot and resolve exact
definition/feature/component/occurrence targets. Glass cannot share a target with
@@ -43,6 +44,14 @@ will admit that request. No renderer or document-format cap is raised by this
capability summary. See [CPU profiles](render-cpu-resource-profiles.md),
[general Glass](render-cpu-general-glass.md), [GPU boundaries](render-glass-boundaries.md),
[shadow connections](render-glass-shadows.md) and [clear coat](render-clear-coat.md).
+The [detailed Glass matrix](render-glass-complete.md) describes the current
+dielectric contract, charged Path sheet tessellations, actual uploaded-GPU
+geometry certification and reproducible CPU/GPU examples. The
+[material-model guide](render-glass-material-models.md) covers rough transmission,
+three-band dispersion, coherent single-layer films and finite-radius hard-source
+caustics. These are not dense spectral integration or an unbiased general
+specular-chain solver. Their new source and headless evidence are qualified
+separately from the historical results below.
<a id="qualification"></a>
@@ -86,7 +95,7 @@ These are current source behaviors in this change. See
qualification by exact source and executed scope. The historical 00ed/CI7 results
and opaque native fixture above remain separate.
-Closed CPU shadow approximation, rough transmission, complete Path selected
-reflection/anisotropy parity, external-map import, refracted caustics and a
-production Glass denoiser remain separate work. Unsupported guards cannot be
-removed to manufacture those capabilities.
+Closed CPU shadow approximation, complete Path selected reflection/anisotropy
+parity, external-map import, dense spectral transport, general unbiased caustics
+and a production Glass denoiser remain separate work. Unsupported guards cannot
+be removed to manufacture those capabilities.
diff --git a/docs/render-transmission.md b/docs/render-transmission.md
index 7238b799ee..8d6ed1277d 100644
--- a/docs/render-transmission.md
+++ b/docs/render-transmission.md
@@ -36,6 +36,11 @@ Boundary is one of:
uses thickness divided by the refracted cosine. Incoherent internal reflections
are summed separately for s/p polarization, then averaged. Zero thickness is
admitted and has no absorption, but retains the two-interface optical response.
+ The exact index-matched, zero-thickness grazing limit has unit transmission.
+ Positive thickness at an exactly tangent, index-matched interface has no finite
+ traversal distance and refuses through the existing transport diagnostic.
+ CPU Path sheets use a charged exact planar/manifold tessellation certificate;
+ the legacy CPU route keeps its one/two-triangle domain.
- `"closed_box"` with `"thickness_mm":0`: strict axis-aligned bounding-plane check (1e-6 mm tolerance),
followed by the GPU's closed, outward two-manifold topology validation.
- `"closed_mesh"` with `"thickness_mm":0`: general closed meshes under the selected
@@ -82,8 +87,13 @@ out-of-range values are errors.
GPU transport uses geometric winding for entering/leaving media, exact s/p Fresnel
including total internal reflection, Snell refraction and Beer attenuation. It
-includes the squared IOR ratio for radiance transport. Glass is smooth; rough
-transmission and fractional mixtures are absent. Runtime [glass shadow connections](render-glass-shadows.md)
+includes the squared IOR ratio for radiance transport. Glass without an optional
+material model remains smooth. An explicit `model` adds isotropic GGX rough
+reflection/transmission, bounded Abbe/Cauchy dispersion and one lossless coherent
+thin-film coating. These use three representative RGB wavelengths, not dense
+spectral integration. Fractional opaque/transmitting mixtures remain absent.
+See [Glass material models](render-glass-material-models.md) for the wire fields,
+models and finite-radius photon caustics. Runtime [glass shadow connections](render-glass-shadows.md)
are enabled by default for thin sheets and opt-in for solids; the latter are explicitly
straight-through NEE-only approximations, not caustics. The maximum path depth remains 16.
The existing bounded per-path stack is retained. Default mode rejects nested